Part Number Hot Search : 
TPC22 78L06 2SD850 Y277G 2SC5419 IRLZ24 C3289 IRLZ24
Product Description
Full Text Search
 

To Download CC78K0S Datasheet File

  If you can't view the Datasheet, Please click here to try to view without PDF Reader .  
 
 


  Datasheet File OCR Text:
 User's Manual
CC78K0S
C Compiler Ver.1.30 or Later Language Target Devices 78K/0S Series
Document No. U14872EJ1V0UM00 (1st edition) Date Published January 2001 N CP(K)
(c)
Printed in Japan
2001
[MEMO]
2
User's Manual U14872EJ1V0UM
Windows and Windows NT are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. PC/AT is a trademark of International Business Machines Corporation. i386 is a trademark of Intel Corporation. UNIX is a registered trademark in the United States and other countries, licensed exclusively through X/Open Company Limited. SPARCstation is a trademark of SPARC International, Inc. SunOS and Solaris are trademarks of Sun Microsystems, Inc. HP9000 series 700 and HP-UX are trademarks of Hewlett-Packard Company.
User's Manual U14872EJ1V0UM
3
* The information in this document is current as of November, 2000. The information is subject to change without notice. For actual design-in, refer to the latest publications of NEC's data sheets or data books, etc., for the most up-to-date specifications of NEC semiconductor products. Not all products and/or types are available in every country. Please check with an NEC sales representative for availability and additional information. * No part of this document may be copied or reproduced in any form or by any means without prior written consent of NEC. NEC assumes no responsibility for any errors that may appear in this document. * NEC does not assume any liability for infringement of patents, copyrights or other intellectual property rights of third parties by or arising from the use of NEC semiconductor products listed in this document or any other liability arising from the use of such products. No license, express, implied or otherwise, is granted under any patents, copyrights or other intellectual property rights of NEC or others. * Descriptions of circuits, software and other related information in this document are provided for illustrative purposes in semiconductor product operation and application examples. The incorporation of these circuits, software and information in the design of customer's equipment shall be done under the full responsibility of customer. NEC assumes no responsibility for any losses incurred by customers or third parties arising from the use of these circuits, software and information. * While NEC endeavours to enhance the quality, reliability and safety of NEC semiconductor products, customers agree and acknowledge that the possibility of defects thereof cannot be eliminated entirely. To minimize risks of damage to property or injury (including death) to persons arising from defects in NEC semiconductor products, customers must incorporate sufficient safety measures in their design, such as redundancy, fire-containment, and anti-failure features. * NEC semiconductor products are classified into the following three quality grades: "Standard", "Special" and "Specific". The "Specific" quality grade applies only to semiconductor products developed based on a customer-designated "quality assurance program" for a specific application. The recommended applications of a semiconductor product depend on its quality grade, as indicated below. Customers must check the quality grade of each semiconductor product before using it in a particular application. "Standard": Computers, office equipment, communications equipment, test and measurement equipment, audio and visual equipment, home electronic appliances, machine tools, personal electronic equipment and industrial robots "Special": Transportation equipment (automobiles, trains, ships, etc.), traffic control systems, anti-disaster systems, anti-crime systems, safety equipment and medical equipment (not specifically designed for life support) "Specific": Aircraft, aerospace equipment, submersible repeaters, nuclear reactor control systems, life support systems and medical equipment for life support, etc. The quality grade of NEC semiconductor products is "Standard" unless otherwise expressly specified in NEC's data sheets or data books, etc. If customers wish to use NEC semiconductor products in applications not intended by NEC, they must contact an NEC sales representative in advance to determine NEC's willingness to support a given application. (Note) (1) "NEC" as used in this statement means NEC Corporation and also includes its majority-owned subsidiaries. (2) "NEC semiconductor products" means any semiconductor product developed or manufactured by or for NEC (as defined above).
M8E 00. 4
4
User's Manual U14872EJ1V0UM
Regional Information
Some information contained in this document may vary from country to country. Before using any NEC product in your application, pIease contact the NEC office in your country to obtain a list of authorized representatives and distributors. They will verify:
* * * * *
Device availability Ordering information Product release schedule Availability of related technical literature Development environment specifications (for example, specifications for third-party tools and components, host computers, power plugs, AC supply voltages, and so forth) Network requirements
*
In addition, trademarks, registered trademarks, export restrictions, and other legal issues may also vary from country to country.
NEC Electronics Inc. (U.S.)
Santa Clara, California Tel: 408-588-6000 800-366-9782 Fax: 408-588-6130 800-729-9288
NEC Electronics (Germany) GmbH
Benelux Office Eindhoven, The Netherlands Tel: 040-2445845 Fax: 040-2444580
NEC Electronics Hong Kong Ltd.
Hong Kong Tel: 2886-9318 Fax: 2886-9022/9044
NEC Electronics Hong Kong Ltd. NEC Electronics (France) S.A.
Velizy-Villacoublay, France Tel: 01-30-67 58 00 Fax: 01-30-67 58 99 Seoul Branch Seoul, Korea Tel: 02-528-0303 Fax: 02-528-4411
NEC Electronics (Germany) GmbH
Duesseldorf, Germany Tel: 0211-65 03 02 Fax: 0211-65 03 490
NEC Electronics (France) S.A. NEC Electronics (UK) Ltd.
Milton Keynes, UK Tel: 01908-691-133 Fax: 01908-670-290 Madrid Office Madrid, Spain Tel: 91-504-2787 Fax: 91-504-2860
NEC Electronics Singapore Pte. Ltd.
United Square, Singapore Tel: 65-253-8311 Fax: 65-250-3583
NEC Electronics Taiwan Ltd. NEC Electronics Italiana s.r.l.
Milano, Italy Tel: 02-66 75 41 Fax: 02-66 75 42 99
NEC Electronics (Germany) GmbH
Scandinavia Office Taeby, Sweden Tel: 08-63 80 820 Fax: 08-63 80 388
Taipei, Taiwan Tel: 02-2719-2377 Fax: 02-2719-5951
NEC do Brasil S.A.
Electron Devices Division Guarulhos-SP Brasil Tel: 55-11-6462-6810 Fax: 55-11-6462-6829
J00.7
User's Manual U14872EJ1V0UM
5
INTRODUCTION
The CC78K0S C Compiler (hereafter referred to as this C compiler) was developed based on CHAPTER 2 ENVIRONMENT and CHAPTER 3 LANGUAGE in the Draft Proposed American National Standard for Therefore, by compiling C source Information Systems -- Programming Language C (December 7, 1988). developed. The CC78K0S C Compiler Language (this manual) has been prepared to give those who develop software by using this C compiler a correct understanding of the basic functions and language specifications of this C compiler. This manual does not cover how to operate this C compiler. Therefore, after you have comprehended the contents of this manual, read the CC78K0S C Compiler Operation (U14871E). For the architecture of 78K/0S Series, refer to the user's manual of each product of 78K/0S Series.
programs conforming to the ANSI standard with this C compiler, 78K/0S Series application products can be
6
User's Manual U14872EJ1V0UM
[Target Devices] Software for the 78K/0S Series microcontrollers can be developed with this C compiler. Note that an optional device file corresponding to the target device is necessary. [Readers] Although this manual is intended for those who have read the user's manual of the microcontroller subject to software development and have experience in software programming, the readers need not necessarily have a knowledge of C compilers or C language. terminology. [Organization] This manual consists of the following 13 chapters and appendixes: CHAPTER 1 GENERAL Outlines the general functions of C compilers and the performance characteristics and features of this C compiler. CHAPTER 2 CHAPTER 3 CONSTRUCTS OF C LANGUAGE Explains the constituting elements of a C source module file. DECLARATION OF TYPES AND STORAGE CLASSES Explains the data types and storage classes used in C and how to declare the type and storage class of a data object or function. CHAPTER 4 CHAPTER 5 CHAPTER 6 CHAPTER 7 CHAPTER 8 CHAPTER 9 TYPE CONVERSIONS Explains the conversions of data types to be automatically carried out by this C compiler. OPERATORS AND EXPRESSIONS Describes the operators and expressions that can be used in C and the precedence of operators. CONTROL STRUCTURES OF C LANGUAGE Explains the program control structures of C and the statements to be executed in C. STRUCTURES AND UNIONS Explains the concept of structures and unions and how to refer to structure and union members. EXTERNAL DEFINITIONS Describes the types of external definitions and how to use external declarations. PREPROCESSING DIRECTIVES Details the types of preprocessing directives and how to use each preprocessing directive. CHAPTER 10 LIBRARY FUNCTIONS Details the types of C library functions and how to use each library function. CHAPTER 11 EXTENDED FUNCTIONS Explains the extended functions of this C compiler that enable users to make the most of the target device. CHAPTER 12 REFERENCING BETWEEN ASSEMBLER AND COMPATIBLES Describes the method of linking a C source program with a program written in Assembly language. CHAPTER 13 EFFECTIVE UTILIZATION OF COMPILER Outlines how to effectively use this C compiler. APPENDIXES A through E Contains a list of labels for saddr area, a list of segment names, a list of runtime libraries, a list of library stack consumption, and index for quick reference. Discussions in this manual assume that the readers are familiar with software
User's Manual U14872EJ1V0UM
7
[How to Use This Manual] * For those who are not familiar with C compilers or C language: Read from CHAPTER 1, as this manual covers from the program control structures of C to the extended functions of this C compiler. In CHAPTER 1, an example of a C source program is used to show the reference part in this manual. * For those who are familiar with C compilers or C language: The language specifications of this C compiler conform to the ANSI Standard C. Therefore, you may start from CHAPTER 11, which explains the extended functions unique to this C compiler. When reading CHAPTER 11, also refer to the user's manual supplied with the target device in the 78K/0S Series if necessary. [Related Documents]
Document Name CC78K0S C Compiler Operation User's Manual Document No. U14871E
[Reference] Draft Proposed American National Standard for Information Systems - Programming Language C (December 7, 1988) [Terms] RTOS = 78K/0 Series Real-Time OS RX78K0 [Conventions] The following symbols and abbreviations are used in this manual: Symbol " ` ... / \ [ ] " ' Meaning Continuation (repetition) of data in the same format Characters enclosed in a pair of double quotes must be input as is. Characters enclosed in a pair of single quotes must be input as is. This part of the program description is omitted. Delimiter Backslash Parameters in square brackets may be omitted.
8
User's Manual U14872EJ1V0UM
CONTENTS
CHAPTER 1 1.1 1.2 1.3 1.4 1.5
GENERAL...........................................................................................................................21
C Language and Assembly Language.........................................................................................21 Program Development Procedure by C Compiler......................................................................23 Basic Structure of C Source Program .........................................................................................25
1.3.1 Program format.................................................................................................................................25
Reminders Before Program Development ..................................................................................28 Features of This C Compiler ........................................................................................................30
(1) (2) (3) (4) (5) (6) (7) (8) (9) callt/_ _callt functions ..........................................................................................................................30 Register variables .................................................................................................................................30 Usage of saddr area.............................................................................................................................30 sfr area .................................................................................................................................................30 noauto functions...................................................................................................................................31 norec/_ _leaf functions.........................................................................................................................31 bit type variables and boolean/_ _boolean type variables ..................................................................31 ASM statements....................................................................................................................................31 Interrupt functions .................................................................................................................................31
(10) Interrupt function qualifier .....................................................................................................................31 (11) Interrupt functions .................................................................................................................................31 (12) CPU control instructions .......................................................................................................................31 (13) Absolute address access function ........................................................................................................31 (14) Bit field declaration ...............................................................................................................................31 (15) Function to change compiler output section name ...............................................................................32 (16) Binary constant description function .....................................................................................................32 (17) Module name change functions ............................................................................................................32 (18) Rotate function......................................................................................................................................32 (19) Multiplication function............................................................................................................................32 (20) Division function....................................................................................................................................32 (21) BCD operation function.........................................................................................................................32 (22) Data insertion function ..........................................................................................................................32 (23) Static model ..........................................................................................................................................32 (24) Type modification..................................................................................................................................32 (25) Pascal function (_ _pascal) ..................................................................................................................32 (26) Automatic pascal functionization of function call interface....................................................................32 (27) Method of int expansion limitation of argument/return value ................................................................33 (28) Array offset calculation simplification method.......................................................................................33 (29) Register direct reference function .........................................................................................................33 (30) Memory manipulation function ..............................................................................................................33 (31) Absolute address allocation specification .............................................................................................33 (32) Static model expansion specification ....................................................................................................33
User's Manual U14872EJ1V0UM
9
(33) Temporary variables .............................................................................................................................33 (34) Library supporting prologue/epilogue....................................................................................................33
CHAPTER 2 2.1
CONSTRUCTS OF C LANGUAGE .................................................................................34
Character Sets .............................................................................................................................. 35
(1) (2) (3) Character sets.......................................................................................................................................35 escape sequences ................................................................................................................................36 Trigraph sequences ..............................................................................................................................36
2.2
Keywords....................................................................................................................................... 37
(1) (2) ANSI-C keywords ..................................................................................................................................37 Keywords added for the CC78K0S .......................................................................................................37 Scope of identifiers ...........................................................................................................................39 (1) (2) (3) (4) 2.3.2 (1) (2) (3) 2.3.3 2.3.4 Function scope ........................................................................................................................39 File scope ................................................................................................................................39 Block scope .............................................................................................................................40 Function prototype scope ........................................................................................................40 External linkage.......................................................................................................................40 Internal linkage ........................................................................................................................40 No linkage ...............................................................................................................................40
2.3
Identifiers....................................................................................................................................... 38
2.3.1
Linkage of identifiers.........................................................................................................................40
Name space for identifiers ................................................................................................................41 Storage duration of objects...............................................................................................................41 (1) (2) Static storage duration ............................................................................................................41 Automatic storage duration .....................................................................................................41 Basic types ..............................................................................................................................42 Character types .......................................................................................................................46 Incomplete types .....................................................................................................................46 Derived types ..........................................................................................................................46 Scalar types.............................................................................................................................47 Compatible type ......................................................................................................................48 Composite type .......................................................................................................................48
2.3.5
Data types.........................................................................................................................................41 (1) (2) (3) (4) (5)
2.3.6
Compatible type and composite type................................................................................................48 (1) (2)
2.4
Constants ...................................................................................................................................... 49
2.4.1 2.4.2 Floating-point constant .....................................................................................................................49 Integer constant ................................................................................................................................49 (1) (2) (3) 2.4.3 2.4.4 Decimal constant.....................................................................................................................49 Octal constant .........................................................................................................................50 Hexadecimal constant .............................................................................................................50
Enumeration constants .....................................................................................................................50 Character constants..........................................................................................................................51
2.5 2.6 10
String Literal.................................................................................................................................. 51 Operators....................................................................................................................................... 51
User's Manual U14872EJ1V0UM
2.7 2.8 2.9
Delimiters .......................................................................................................................................52 Header Name..................................................................................................................................52 Comment ........................................................................................................................................52
CHAPTER 3 3.1
DECLARATION OF TYPES AND STORAGE CLASSES .............................................53
Storage Class Specifiers ..............................................................................................................54
(1) (2) (3) (4) (5) typedef ..................................................................................................................................................54 extern ....................................................................................................................................................54 static .....................................................................................................................................................54 auto .......................................................................................................................................................54 register ..................................................................................................................................................54 Structure specifier and union specifier .............................................................................................57 (1) (2) (3) 3.2.2 3.2.3 Structure specifier ...................................................................................................................57 Union specifier ........................................................................................................................57 Bit field ....................................................................................................................................58
3.2
Type Specifiers ..............................................................................................................................55
3.2.1
Enumeration specifiers .....................................................................................................................59 Tags..................................................................................................................................................60
3.3 3.4
Type Qualifiers...............................................................................................................................61 Declarators.....................................................................................................................................62
3.4.1 3.4.2 3.4.3 Pointer declarators ...........................................................................................................................62 Array declarators ..............................................................................................................................63 Function declarators (including prototype declarations) ...................................................................63
3.5 3.6 3.7
Type Names ...................................................................................................................................64 typedef Declarations .....................................................................................................................65 Initialization....................................................................................................................................67
(1) (2) (3) (4) Initialization of objects which have a static storage duration ................................................................67 Initialization of objects which have an automatic storage duration .......................................................67 Initialization of character arrays ............................................................................................................67 Initialization of aggregate or union type objects....................................................................................68
CHAPTER 4 4.1
TYPE CONVERSIONS ......................................................................................................70
Arithmetic Operands .....................................................................................................................72
(1) (2) (3) Characters and integers (general integral promotion) ..........................................................................72 Signed integers and unsigned integers ................................................................................................72 Usual arithmetic type conversions ........................................................................................................73
4.2
Other Operands .............................................................................................................................74
(1) (2) (3) Left-side values and function locators ..................................................................................................74 void .......................................................................................................................................................74 Pointers.................................................................................................................................................74
CHAPTER 5
OPERATORS AND EXPRESSIONS ................................................................................75 11
User's Manual U14872EJ1V0UM
5.1 5.2
Primary Expressions .................................................................................................................... 78 Postfix Operators.......................................................................................................................... 78
(1) (2) (3) (4) Subscript operator.................................................................................................................................79 Function call ..........................................................................................................................................80 Structure and union member.................................................................................................................81 Postfix increment/decrement operators ................................................................................................83
5.3
Unary Operators ........................................................................................................................... 84
(1) (2) (3) (4) Prefix increment/decrement operators ..................................................................................................85 Address and indirect operators .............................................................................................................86 Unary arithmetic operators (+ - ~ !) ......................................................................................................87 sizeof operator ......................................................................................................................................88
5.4 5.5
Cast Operator................................................................................................................................ 89 Arithmetic Operators .................................................................................................................... 90
(1) (2) Multiplicative operators .........................................................................................................................91 Additive operators .................................................................................................................................92
5.6 5.7
Bitwise Shift Operators ................................................................................................................ 93 Relational Operators .................................................................................................................... 95
(1) (2) Relational operators ..............................................................................................................................96 Equality operators .................................................................................................................................98
5.8
Bitwise Logical Operators ........................................................................................................... 99
(1) (2) (3) Bitwise AND operator ..........................................................................................................................100 Bitwise XOR operator..........................................................................................................................101 Bitwise inclusive OR operator .............................................................................................................102
5.9
Logical Operators ....................................................................................................................... 103
(1) (2) Logical AND operator..........................................................................................................................104 Logical OR operator ............................................................................................................................105
5.10 Conditional Operators................................................................................................................ 106 5.11 Assignment Operators ............................................................................................................... 107
(1) (2) Simple assignment operator ...............................................................................................................108 Compound assignment operators .......................................................................................................109
5.12 Comma Operator ........................................................................................................................ 110 5.13 Constant Expressions................................................................................................................ 111
(1) (2) (3) General integral constant expression..................................................................................................111 Arithmetic constant expression ...........................................................................................................111 Address constant expression ..............................................................................................................111
CHAPTER 6 6.1
CONTROL STRUCTURES OF C LANGUAGE............................................................112
Labeled Statements.................................................................................................................... 114
(1) (2) case label ............................................................................................................................................115 default label.........................................................................................................................................117
6.2 6.3 6.4 12
Compound Statements (Blocks) ............................................................................................... 118 Expression Statements and Null Statements .......................................................................... 118 Selection Statements ................................................................................................................. 119
User's Manual U14872EJ1V0UM
(1) (2)
if and if ... else statements ..................................................................................................................120 switch statement .................................................................................................................................121
6.5
Iteration Statements ....................................................................................................................122
(1) (2) (3) while statement ...................................................................................................................................123 do statement .......................................................................................................................................124 for statement .......................................................................................................................................125
6.6
Branch Statements......................................................................................................................126
(1) (2) (3) (4) goto statement ....................................................................................................................................127 continue statement .............................................................................................................................128 break statement ..................................................................................................................................129 return statement..................................................................................................................................130
CHAPTER 7 7.1
STRUCTURES AND UNIONS........................................................................................131
Structures.....................................................................................................................................132
(1) (2) (3) (4) Declaration of structure and structure variable ...................................................................................132 Structure declaration list .....................................................................................................................132 Arrays and pointers.............................................................................................................................133 How to refer to structure members .....................................................................................................133
7.2
Unions ..........................................................................................................................................134
(1) (2) (3) (4) Declaration of union and union variable..............................................................................................134 Union declaration list ..........................................................................................................................134 Union arrays and pointers...................................................................................................................135 How to refer to union members...........................................................................................................135
CHAPTER 8 8.1 8.2
EXTERNAL DEFINITIONS ..............................................................................................137
Function Definitions....................................................................................................................138 External Object Definitions ........................................................................................................140
CHAPTER 9 9.1
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES) ....................................141
Conditional Inclusion ..................................................................................................................142
(1) (2) (3) (4) (5) (6) #if directive..........................................................................................................................................143 #elif directive .......................................................................................................................................144 #ifdef directive.....................................................................................................................................145 #ifndef directive...................................................................................................................................146 #else directive .....................................................................................................................................147 #endif directive....................................................................................................................................148
9.2
Source File Inclusion ..................................................................................................................149
(1) (2) (3) #include < > directive .........................................................................................................................150 #include " " directive...........................................................................................................................151 #include preprocessing token string directive.....................................................................................152
9.3
Macro Replacement ....................................................................................................................153
User's Manual U14872EJ1V0UM
13
(1) (2) (3) (4) (5) (6) (7) (8)
Actual argument replacement .............................................................................................................153 # operator............................................................................................................................................153 ## operator..........................................................................................................................................153 Re-scanning and further replacement.................................................................................................154 Scope of macro definition....................................................................................................................154 #define directive ..................................................................................................................................155 #define ( ) directive.............................................................................................................................156 #undef directive...................................................................................................................................157
9.4
Line Control................................................................................................................................. 158
(1) (2) (3) To change the line number .................................................................................................................158 To change the line number and the file name.....................................................................................158 To change using preprocessor token string ........................................................................................158
9.5 9.6 9.7 9.8
#error Preprocessing Directive ................................................................................................. 159 #pragma Directive....................................................................................................................... 160 Null Directive............................................................................................................................... 160 Predefined Macro Names........................................................................................................... 161
CHAPTER 10
LIBRARY FUNCTIONS..................................................................................................163
10.1 Interface Between Functions..................................................................................................... 164
10.1.1 10.1.2 10.1.3 Arguments ......................................................................................................................................164 Return values..................................................................................................................................165 Saving registers to be used by individual libraries ..........................................................................165 (1) (2) No -ZR option specified.........................................................................................................166 -ZR option specified ..............................................................................................................167
10.2 Headers........................................................................................................................................ 171
(1) (2) (3) (4) (5) (6) (7) (8) (9) ctype.h.................................................................................................................................................172 setjmp.h...............................................................................................................................................173 stdarg.h (normal model only) ..............................................................................................................174 stdio.h..................................................................................................................................................174 stdlib.h.................................................................................................................................................175 string.h ................................................................................................................................................177 error.h..................................................................................................................................................178 errno.h.................................................................................................................................................178 limits.h .................................................................................................................................................178
(10) stddef.h ...............................................................................................................................................180 (11) math.h (normal model only) ................................................................................................................181 (12) float.h ..................................................................................................................................................183 (13) assert.h (normal model only)...............................................................................................................185
10.3 Re-entrantability (Normal Model Only) ..................................................................................... 185
(1) (2) (3) Functions that cannot be re-entranced ...............................................................................................185 Functions that use the area secured in the startup routine .................................................................185 Functions that deal with floating-point numbers..................................................................................185
14
User's Manual U14872EJ1V0UM
10.4 Standard Library Functions........................................................................................................186 10.5 Batch Files for Update of Startup Routine and Library Functions.........................................296
10.5.1 Using batch files .............................................................................................................................297
CHAPTER 11
EXTENDED FUNCTIONS..............................................................................................300
11.1 Macro Names ...............................................................................................................................301 11.2 Keywords .....................................................................................................................................302
(1) (2) Functions ............................................................................................................................................302 Variables .............................................................................................................................................303
11.3 Memory.........................................................................................................................................304
(1) (2) (3) Memory model ....................................................................................................................................304 Register bank......................................................................................................................................304 Memory space ....................................................................................................................................304
11.4 #pragma Directive .......................................................................................................................306 11.5 How to Use Extended Functions ...............................................................................................308
(1) (2) (3) (4) (5) (6) (7) (8) (9) callt functions ......................................................................................................................................309 Register variables ...............................................................................................................................312 How to use the saddr area..................................................................................................................316 How to use the sfr area.......................................................................................................................323 noauto function ...................................................................................................................................326 norec function .....................................................................................................................................330 bit type variables .................................................................................................................................335 ASM statements..................................................................................................................................339 Interrupt functions ...............................................................................................................................342
(10) Interrupt function qualifier (_ _interrupt)..............................................................................................349 (11) Interrupt functions ...............................................................................................................................351 (12) CPU control instruction .......................................................................................................................354 (13) Absolute address access function ......................................................................................................356 (14) Bit field declaration .............................................................................................................................360 (15) Changing compiler output section name ............................................................................................368 (16) Binary constant ....................................................................................................................................379 (17) Module name changing function ..........................................................................................................381 (18) Rotate function .....................................................................................................................................382 (19) Multiplication function...........................................................................................................................385 (20) Division function ...................................................................................................................................387 (21) BCD operation function ........................................................................................................................390 (22) Data insertion function .........................................................................................................................394 (23) Static model .........................................................................................................................................396 (24) Type modification .................................................................................................................................400 (25) Pascal function.....................................................................................................................................402 (26) Automatic pascal functionization of function call interface...................................................................405 (27) Method of int expansion limitation of argument/return value................................................................406
User's Manual U14872EJ1V0UM
15
(28) Array offset calculation simplification method ......................................................................................409 (29) Register direct reference function ........................................................................................................411 (30) Memory manipulation function .............................................................................................................415 (31) Absolute address allocation specification ............................................................................................418 (32) Static model expansion specification ...................................................................................................422 (33) Temporary variables.............................................................................................................................432 (34) Library supporting prologue/epilogue ...................................................................................................435
11.6 Modifications of C Source ......................................................................................................... 444 11.7 Function Call Interface ............................................................................................................... 445
11.7.1 11.7.2 Return value....................................................................................................................................446 Ordinary function call interface .......................................................................................................447 (1) (2) (3) 11.7.3 (1) (2) (3) 11.7.4 (1) (2) (3) 11.7.5 (1) (2) (3) 11.7.6 Passing arguments................................................................................................................447 Location and order of storing arguments...............................................................................448 Location and order of storing automatic variables.................................................................449 Passing arguments................................................................................................................454 Location and order of storing arguments...............................................................................454 Location and order of storing automatic variables.................................................................455 Passing arguments................................................................................................................457 Location and order of storing arguments...............................................................................457 Location and order of storing automatic variables.................................................................458 Passing arguments................................................................................................................460 Location and order of storing arguments...............................................................................460 Location and order of storing automatic variables.................................................................461
noauto function call interface (normal model only) .........................................................................454
norec function call interface (normal model)...................................................................................457
Static model function call interface .................................................................................................460
Pascal function call interface ..........................................................................................................465
CHAPTER 12
REFERENCING THE ASSEMBLER.............................................................................469
12.1 Accessing Arguments/Automatic Variables ............................................................................ 470
12.1.1 12.1.2 Normal model .................................................................................................................................470 Static model ....................................................................................................................................473
12.2 Storing Return Values ................................................................................................................ 475 12.3 Calling Assembly Language Routines from C Language....................................................... 476 12.4 Calling C Language Routines from Assembly Language....................................................... 480
(1) (2) Calling the C language function from an assembly language program...............................................480 Referencing arguments in a C language function ...............................................................................481
12.5 Referencing Variables Defined in Other Languages............................................................... 482
(1) (2) Referencing variables defined in the C language ...............................................................................482 Referencing variables defined in the assembly language from the C language .................................483
12.6 Cautions ...................................................................................................................................... 484
(1) (2) `_' (underscore) ...................................................................................................................................484 Argument positions on the stack .........................................................................................................484
16
User's Manual U14872EJ1V0UM
CHAPTER 13
EFFECTIVE UTILIZATION OF COMPILER................................................................485
13.1 Efficient Coding ...........................................................................................................................485
(1) (2) (3) (4) (5) Using external variable .......................................................................................................................486 1-bit data .............................................................................................................................................486 Function definitions .............................................................................................................................486 Optimization options ...........................................................................................................................487 Using extended description.................................................................................................................487
APPENDIX A
LIST OF LABELS FOR SADDR AREA .....................................................................489
A.1 Normal Model...............................................................................................................................489 A.2 Static Model .................................................................................................................................491
APPENDIX B
LIST OF SEGMENT NAMES .......................................................................................492
B.1 List of Segment Names...............................................................................................................493 B.2 Location of Segment ...................................................................................................................493 B.3 Example of C Source...................................................................................................................494 B.4 Example of Output Assembler Module .....................................................................................495
APPENDIX C
LIST OF RUNTIME LIBRARIES ..................................................................................499
APPENDIX D
LIST OF LIBRARY STACK CONSUMPTION ............................................................505
APPENDIX E INDEX ...............................................................................................................................514
User's Manual U14872EJ1V0UM
17
LIST OF FIGURES
Figure No.
Title
Page
1-1 Flow of Compilation ...............................................................................................................................................22 1-2 Program Development Procedure by This C Compiler..........................................................................................24
4-1 Usual Arithmetic Type Conversions.......................................................................................................................73
6-1 Control Flows of Selection Statements ................................................................................................................119 6-2 Control Flows of Iteration Statements..................................................................................................................122 6-3 Control Flows of Branch Statements ...................................................................................................................126
10-1 Stack Area When Function Is Called (No -ZR Specified) ..................................................................................167 10-2 Syntax of Format Commands ............................................................................................................................198 10-3 Syntax of Input Format Commands ...................................................................................................................202
11-1 Bit Allocation by Bit Field Declaration (Example 1)............................................................................................362 11-2 Bit Allocation by Bit Field Declaration (Example 2)............................................................................................363 11-3 Bit Allocation by Bit Field Declaration (Example 3)............................................................................................365
12-1 Stack Area After a Call ......................................................................................................................................476 12-2 Stack Area After Returning ................................................................................................................................479 12-3 Placing Arguments on Stack..............................................................................................................................480 12-4 Passing Arguments to C Language ...................................................................................................................481 12-5 Stack Positions of Arguments............................................................................................................................484
18
User's Manual U14872EJ1V0UM
LIST OF TABLES (1/2)
Table No.
Title
Page
1-1 Maximum Performance Characteristics of This C Compiler ..................................................................................28
2-1 List of Escape Sequences .....................................................................................................................................36 2-2 List of Trigraph Sequence......................................................................................................................................36 2-3 List of Basic Data Types ........................................................................................................................................44 2-4 Exponent Relationships .........................................................................................................................................45 2-5 List of Operation Exceptions ..................................................................................................................................46
4-1 List of Conversions Between Types.......................................................................................................................71 4-2 Conversions from Signed Integral Type to Unsigned Integral Type.......................................................................72
5-1 Evaluation Precedence of Operators .....................................................................................................................77 5-2 Signs of Division/Remainder Operation Result......................................................................................................90 5-3 Shift Operations .....................................................................................................................................................93 5-4 Bitwise AND Operator ..........................................................................................................................................100 5-5 Bitwise XOR Operator..........................................................................................................................................101 5-6 Bitwise OR Operator ............................................................................................................................................102 5-7 Logical AND Operator..........................................................................................................................................104 5-8 Logical OR Operator ............................................................................................................................................105
10-1 List of Passing First Argument (Normal Model) .................................................................................................164 10-2 List of Passing Arguments (Static Model) ..........................................................................................................165 10-3 List of Storing Return Value ...............................................................................................................................165 10-4 Contents of ctype.h ............................................................................................................................................172 10-5 Contents of setjmp.h ..........................................................................................................................................173 10-6 Contents of stdarg.h...........................................................................................................................................174 10-7 Contents of stdio.h .............................................................................................................................................174 10-8 Contents of stdlib.h ............................................................................................................................................175 10-9 Contents of string.h............................................................................................................................................177 10-10 Contents of math.h...........................................................................................................................................181 10-11 Contents of assert.h.........................................................................................................................................185 10-12 Batch Files for Updating Library Functions ......................................................................................................296
User's Manual U14872EJ1V0UM
19
LIST OF TABLES (2/2)
Table No.
Title
Page
11-1 List of Added Keywords .....................................................................................................................................302 11-2 Utilization of Memory Space ..............................................................................................................................305 11-3 List of #pragma Directives .................................................................................................................................307 11-4 The Number of callt Attribute Functions That Can Be Used When the -QL Option Is Specified .......................310 11-5 Restrictions on callt Function Usage .................................................................................................................310 11-6 Restrictions on Register Variable Usage ...........................................................................................................313 11-7 Restrictions on sreg Variable Usage .................................................................................................................317 11-8 Variables Allocated to saddr Area by -RD Option..............................................................................................319 11-9 Variables Allocated to saddr Area by -RS Option ..............................................................................................320 11-10 Variables Allocated to saddr Area by -RK Option ............................................................................................321 11-11 Operators Using Only Constants 0 or 1 (with Bit Type Variable) .....................................................................336 11-12 Save/Restore Area When Interrupt Function Is Used......................................................................................343 11-13 Details of Type Modification (Change from int and short Type to char Type) ..................................................400 11-14 Details of Type Modification (Change from long Type to int Type) ..................................................................401 11-15 Interrupt Functions Targeted for Saving ..........................................................................................................422 11-16 Location of Storing Return Value.....................................................................................................................446 11-17 Location Where First Argument Is Passed (on Function Call Side) ................................................................447 11-18 Areas to Which Arguments Are Passed in Static Model..................................................................................460
12-1 Passing Arguments (Function Call Side) ...........................................................................................................470 12-2 Storing of Arguments/Automatic Variables (Inside Called Function) .................................................................471 12-3 Passing Arguments (Function Call Side) ...........................................................................................................473 12-4 Storing of Arguments/Automatic Variables (Inside Called Function) .................................................................473 12-5 Storage Location of Return Values ....................................................................................................................475
C-1 List of Runtime Libraries .....................................................................................................................................499
D-1 List of Standard Library Stack Consumption .......................................................................................................508 D-2 List of Runtime Library Stack Consumption ........................................................................................................513
20
User's Manual U14872EJ1V0UM
CHAPTER 1
GENERAL
The CC78K0S Series C Compiler is a language processing program which converts a source program written in the C language for the 78K/0S Series or ANSI-C into machine language. Object files or assembler source files for the 78K/0S Series can be obtained by using this CC78K0S Series C compiler.
1.1
C Language and Assembly Language
To have a microcontroller do its job, programs and data are necessary. These programs and data must be written by a human being (programmer) and stored in the memory section of the microcontroller. Programs and data that can be handled by the microcontroller are nothing but a set or combination of binary numbers called machine language. An assembly language is a symbolic language characterized by one-to-one correspondence of its symbolic (mnemonic) statements with machine language instructions. Because of this one-to-one correspondence, the assembly language can provide the computer with detailed instructions (for example, to improve I/O processing speed). However, this means that the programmer must instruct each and every operation of the computer. For this reason, it is difficult to understand the logic structure of the program at glance and the programmer is likely to make errors in coding. High-level languages were developed as substitutes for such assembly languages. The high-level languages include a language called C, which allows the programmer to write a program without regard to the architecture of the computer. As compared with assembly language programs, it can be said that programs written in C have an easy-tounderstand logic structure. C has a rich set of parts called functions for use in creating programs. In other words, the programmer can write a program by combining these functions. C is characterized by its ease of understanding by human beings. However, understanding of languages by the microcontroller cannot be extended up to a program written in C. Therefore, to have the computer understand the C language program, another program is required to translate C language statements into the corresponding machine language instructions. A program that translates the C language into machine language is called a C compiler. This C compiler accepts C source modules as inputs and generates object modules or assembler source modules as outputs. Therefore, the programmer can write a program in C and if he or she wishes to instruct the computer up to details of program execution, the C source program can be modified in assembly language. The flow of translation by this C compiler is illustrated in Figure 1-1.
User's Manual U14872EJ1V0UM
21
CHAPTER 1
GENERAL
Figure 1-1. Flow of Compilation
Program written in C language Program coded in a set of binary numbers
Translating program (Compiler) (C source module file) (Object module file)
(Assembler source module file) Program coded in a set of binary numbers
Translating program (Assembler) (Object module file)
22
User's Manual U14872EJ1V0UM
CHAPTER 1
GENERAL
1.2
Program Development Procedure by C Compiler
Product (program) development by the C compiler requires a linker to unite object module files created by the compiler, a librarian to create library files, and a debugger to locate and correct bugs (errors or mistakes) in each created C source program. The software required in connection with this C compiler is shown below. * Editor .......................................... for source module file creation * RA78K0S assembler package Assembler................................... for converting assembly language into machine language Linker .......................................... for linking object module files for determining location address of relocatable segment Object converter ......................... for conversion to HEX-format object module file Librarian...................................... for creating library files * Debugger (for 78K/0S)................ for debugging C source module files The product development procedure by the C compiler is as shown below. <1> Divides the product into functions. <2> Creates a C source module for each function. <3> Translates each C source module. <4> Registers the modules to be used frequently in the library. <5> Links object module files. <6> Debugs each module. <7> Converts object modules into HEX-format object files. As mentioned earlier, this C compiler translates (compiles) a C source module file and creates an object module file or assembler source module file. By manually optimizing the created assembler source module file and embedding it into the C source, efficient object modules can be created. This is useful when high-speed processing is a must or when modules must be made compact.
User's Manual U14872EJ1V0UM
23
CHAPTER 1
GENERAL
Figure 1-2. Program Development Procedure by This C Compiler
C source Structured assembler source
Include file
Structured assembler
C compiler
Assembler source
Assembler source
Assembler MX78K0S
Object module file
Library file
Librarian
Assemble list
Library file Linker Load module file
List converter
System simulator Object converter Integrated debugger
Absolute assemble list
IR
C U
IT
E
M
U
Hex-format object
IN C
Dedicated parallel interface
LA T O R
In-circuit emulator
POWER
RS-232C
PROM programmer
24
User's Manual U14872EJ1V0UM
CHAPTER 1
GENERAL
1.3
Basic Structure of C Source Program
1.3.1 Program format A C language program is a collection of functions. These functions must be created so that they have independent special-purpose or characteristic actions. All C language programs must have a function main which becomes the main routine in C and is the first function that is called when execution begins. Each function consists of a header part, which defines its function name and arguments, and a body part, which consists of declarations and statements. The format of C programs is shown below. Definition of variables/constants main (arguments) { statement1; statement2; function1 (arguments); function2 (arguments); } function1 (arguments) { statement1; statement2; Function 1 Body of the function main Definition of each data, variable, and macro instruction Header of the function main
} function2 (arguments) { statement1; statement2; } Function 2
User's Manual U14872EJ1V0UM
25
CHAPTER 1
GENERAL
An actual C source program looks like this. #define TRUE #define FALSE #define SIZE 1 0 200 xxx xxxx (xxx, xxx)...................... Function prototype declarator <7> #define xxx xxx ....... Preprocessor directive (macro definition) <6>
void printf(char *,int); void putchar(char); char mark[SIZE+1]; main() { int i,prime,k,count; count=0; for(i=0;i<=SIZE;i++) mark[i]=TRUE; for(i=0;i<=SIZE;i++){ if(mark[i]){ prime=i+i+3; printf("%6d",prime); count++;
char xxx .............. Type declarator
<1>
External definition
<5> <2> <1> <2> <3>
xx [xx]..........................................................................Operator int xxx .............................................................. Type declarator xx = xx.........................................................................Operator for (xx;xx;xx) xxx ;........................................... Control structure
xxx = xxx + xxx + xxx................................................Operator xxx (xxx) ; .................................................................Operator
<2> <2>
if((count%8)==0) putchar('\n'); for(k=i+prime;k<=SIZE;k+=prime) mark[k]=FALSE; } } printf("\n%d primes found.",count); } void printf(char *s,int i) { int j; char *ss; j=i; ss=s; } void putchar(char c) { char d; d=c; }
if (xxx) xxx ; ....................... Control structure
<3>
xxx (xxx) ;........................................Operator
<2>
26
User's Manual U14872EJ1V0UM
CHAPTER 1
GENERAL
<1> Declaration of type and storage class The data type and storage class of an identifier that indicates a data object are declared. For details, see CHAPTER 3 DECLARATION OF TYPES AND STORAGE CLASSES. <2> Operator and expression These are the statements that instruct the compiler to perform operations such as arithmetic operations, logical operations, or assignments. For details, see CHAPTER 5 OPERATORS AND EXPRESSIONS. <3> Control structure This is a statement that specifies the program flow. C has several instructions for each of control structures such as conditional control, iteration, and branch. For details, see CHAPTER 6 CONTROL STRUCTURES OF C LANGUAGE. <4> Structure or union A structure or union is declared. A structure is a data object that contains several subobjects or members that may have different types. A union is defined when two or more variables share the same memory. For details, see CHAPTER 7 STRUCTURES AND UNIONS. <5> External definition A function or external object is declared. A function is one element when a C language program is divided by a special-purpose or characteristic action. A C program is a collection of these functions. For details, see CHAPTER 8 EXTERNAL DEFINITIONS. <6> Preprocessing directive This is an instruction for the compiler. #define instructs the compiler to replace a parameter which is the same as the first operand with the second operand if the parameter appears in the program. For details, see CHAPTER 9 PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES). <7> Declaration of function prototype The return value and argument type of a function are declared.
User's Manual U14872EJ1V0UM
27
CHAPTER 1
GENERAL
1.4
Reminders Before Program Development
Before starting development of a program, keep in mind the points (limit values or minimum guaranteed values) summarized in Table 1-1 below. Table 1-1. Maximum Performance Characteristics of This C Compiler (1/2)
Limit Value/Min. Guaranteed Value 45 levels
No. 1
Item Nesting level of compound statements, looping statements, or conditional control statements Nesting of conditional translations Number of arithmetic type, structure type, pointer to qualify union type or incomplete type, array, and function declarator in a declaration (or any combination of these). Nesting of parentheses per expression Number of characters which have a meaning as a macro name Number of characters which have a meaning as an internal or external symbol name Number of symbols per source module file Number of symbols which has block scope within a block Number of macros per source module file Number of parameters per function definition or function call Number of parameters per macro definition or macro call Number of characters per logical source line Number of characters within a string literal after linkage Size of one data object Nesting of #include directives Number of case labels per switch statement Number of source lines per translation unit Number of source lines that can be translated without temporary file creation Nest of function calls Number of labels within a function
2 3
255 levels 12 levels
4 5 6
32 levels 256 characters 249 characters 1,024 symbolsNote 1 255 symbolsNote 1 10,000 macrosNote 2 39 parameters 31 parameters 2048 characters 509 characters 65,535 bytes 8 levels 257 labels Approx. 30,000 lines Approx. 300 lines
7 8 9 10 11 12 13 14 15 16 17 18
19 20
40 levels 33 labels
Notes 1. This value applies when symbols can be processed with the available memory space alone without using any temporary files. When a temporary file is used because of insufficient memory space, this value must be changed according to the file size. 2. This value includes the reserved macro definitions of the C compiler.
28
User's Manual U14872EJ1V0UM
CHAPTER 1
GENERAL
Table 1-1. Maximum Performance Characteristics of This C Compiler (2/2)
Limit Value/Min. Guaranteed Value 65,535 bytes 256 members 255 constants 15 levels 15 levels 1,000 591
No. 21 22 23 24 25 26 27
Item Total size of code, data, and stack segments per object module Number of members per structure or union Number of enum constants per enumeration Nest of structures or unions inside a structure or union Nest of initializer elements Number of function definitions in 1 source module file Level of the nest of declarator enclosed with parentheses inside a complete declarator. Nest of macros Number of -I include file path specifications
28 29
200 64
User's Manual U14872EJ1V0UM
29
CHAPTER 1
GENERAL
1.5
Features of This C Compiler
This C compiler has extended functions for CPU code generation that is not supported by the ANSI (American National Standards Institute) Standard C. improve program execution speed. FUNCTIONS in this manual. Outlined here are the extended functions used to help shorten object code and improve execution speed. * Functions can be called using the callt table area. .......................................... * Variables can be allocated to registers. ............................................................ * Variables can be allocated to the saddr area................................................... * sfr names can be used. .................................................................................... * Functions that do not output code for stack frame formation can be created. .. * An assembly language program can be described in a C source program ..... . * Accessing the saddr or sfr area can be made on a bit-by-bit basis................. callt /_ _callt functions Register variables sreg/_ _sreg sfr area noauto functions, norec/_ _leaf functions ASM statements bit type variables, boolean/_ _boolean type variables * A bit field can be specified with unsigned char type........................................ * The code to multiply can be directly output with inline expansion..................... * The code to divide can be directly output with inline expansion. ...................... * The code to rotate can be directly output with inline expansion........................ * Specific addresses in the memory space can be accessed. ............................ * Specific data and instructions can be directly embedded in the code area. ..... * The used stack is corrected on the called function side. .................................. Bit field declaration Multiplication function Division function Rotate function Absolute address function Data insertion function _ _pascal function The extended functions of the C compiler allow the special function EXTENDED registers for the 78K/0S Series to be described at the C language level and thus help shorten object code and For details of these extended functions, see CHAPTER 11
An outline of the expansion functions of this compiler is shown below. For details of each expansion function, refer to CHAPTER 11. (1) callt/_ _callt functions Functions can be called by using the callt table area. The address of each function to be called (this function is called a callt function) is stored in the callt table from which it can be called later. This makes the object code shorter than for the ordinary call instruction call. (2) Register variables Variables declared with the register storage class specifier are allocated to the register or saddr area. Instructions to the variables allocated to the register or saddr area are shorter in code length than those to memory. This helps shorten object and improves program execution speed as well. (3) Usage of saddr area Variables declared with the keyword sreg can be allocated to the saddr area. Instructions to these sreg variables are shorter in code length than those to memory. This helps shorten object code and also improves program execution speed. Variables can be allocated to the saddr area also by option. (4) sfr area By declaring use of sfr names, manipulations on the sfr area can be described in the C source file.
30
User's Manual U14872EJ1V0UM
CHAPTER 1
GENERAL
(5) noauto functions Functions declared as noauto do not output code for preprocessing and postprocessing (stack frame formation). By calling a noauto function, arguments are passed via registers. This helps shorten object code and improve program execution speed as well. This function has restrictions with argument/automatic variables. For the details, refer to Section 11.5 (5) noauto function. (6) norec/_ _leaf functions Functions declared as norec/_ _leaf do not output code for preprocessing and postprocessing (stack frame formation). By calling a norec/_ _leaf function, arguments are passed via registers as much as possible. Automatic variables to be used inside a norec/_ _leaf function are allocated to registers or the saddr area. This helps shorten object code and also improve program execution speed. This function has restrictions with argument/automatic variables and is not allowed to call a function. For the details, refer to Section 11.5 (6) norec function. (7) bit type variables and boolean/_ _boolean type variables Variables having a 1-bit storage area are generated. By using the bit type variable or boolean/_ _boolean type variable, the saddr area can be accessed in bit units. The boolean/_ _boolean type variable is the same as the bit type variable in terms of both function and usage. (8) ASM statements The assembler source program described by the user can be embedded in an assembler source file to be output by this C compiler. (9) Interrupt functions The preprocessing directive outputs a vector table and outputs an object code corresponding to the interrupt. This directive allows programming of interrupt functions at the C source level. (10) Interrupt function qualifier This qualifier allows the setting of a vector table and interrupt function definitions to be described in a separate file. (11) Interrupt functions An interrupt disable instruction and an interrupt enable instruction are embedded in objects. (12) CPU control instructions Each of the following instructions is embedded in objects: Instruction to set the value for halt to the STBC register Instruction to set the value for stop to the STBC register nop instruction (13) Absolute address access function Codes that access the ordinary memory space are created through direct inline expansion without resort to a function call, and an object file is created. (14) Bit field declaration By specifying a bit field to be unsigned char type, the memory can be saved, object code can be shortened, and execution speed can be improved.
User's Manual U14872EJ1V0UM
31
CHAPTER 1
GENERAL
(15) Function to change compiler output section name By changing the compiler section output name, the section can be independently allocated with a linker. (16) Binary constant description function Binary can be described in the C source. (17) Module name change functions Object module names can be freely changed in the C source. (18) Rotate function The code to rotate the value of an expression to the object can be directly output with inline expansion. (19) Multiplication function The code to multiply the value of an expression to the object can be directly output with inline expansion. This function can shorten the object code and improve the execution speed. (20) Division function The code to divide the value of an expression to the object can be directly output with inline expansion. This function can shorten the object code and improve the execution speed. (21) BCD operation function This function uses direct inline expansion to output the code that performs a BCD operation on the operation value in an object. A BCD operation is an operation for converting each digit of a decimal number into binary and storing it in 4 bits. (22) Data insertion function Constant data is inserted in the current address. Specific data and instructions can be embedded in the code area without using assembler description. (23) Static model Specifying the -SM option during compilation enables the shortening of object codes, improvement of execution speed, realization of high-speed interrupt processing, and saving of memory space. (24) Type modification By specifying the -ZI option and -ZL option, int/short types are regarded as char type, and long type is regarded as int type. (25) Pascal function (_ _pascal) The stack correction used for placing arguments during the function call is performed on the function callee, not on the function caller. This shortens the object code when a lot of function call appears. (26) Automatic pascal functionization of function call interface By specifying the -ZR option during compilation, the _ _pascal attribute is added to functions other than the norec/_ _interrupt/variable length argument functions.
32
User's Manual U14872EJ1V0UM
CHAPTER 1
GENERAL
(27) Method of int expansion limitation of argument/return value By specifying the -ZB option during compilation, the object code can be shortened and execution speed can be improved. (28) Array offset calculation simplification method By specifying the -QW2, -QW3, -QW4, and -QW5 options during compilation, the offset calculation code is simplified, the object code is shortened, and the execution speed is improved. (29) Register direct reference function Register access can be made easily by the C specification by coding this function in the source in the same format as the function call or by declaring the use of this register direct reference function by the #pragma realregister directive in the module. (30) Memory manipulation function By the #pragma inline directive, an object file is generated by the output of the standard library functions memcpy and memset with direct inline expansion instead of function call. execution speed. (31) Absolute address allocation specification By declaring _ _directmap in the module in which the variable to be allocated to an absolute address is to be defined, one or more variables can be allocated to the same arbitrary address. (32) Static model expansion specification By specifying the -ZM option during compilation, restrictions on existing static models can be relaxed, improving descriptiveness. (33) Temporary variables By specifying the -SM and -ZM options during compilation and declaring _ _temp for arguments and automatic variables, an area for arguments and automatic variables can be reserved. In addition, if the sections containing arguments and those containing automatic variables are clearly identified and the _ _temp declaration is applied to variables that do not require a guaranteed value match before and after a function call, memory can be reserved. (34) Library supporting prologue/epilogue By specifying the -ZD option during compilation, the prologue/epilogue code can be replaced by a library, shortening the object code. This function can improve the
User's Manual U14872EJ1V0UM
33
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
This chapter explains the constituting elements of a C source module file. A C source module file consists of the following tokens (distinguishable units in a sequence of characters). Keywords String literal Header name Identifiers Operators No. of preprocesses Constants Delimiters Comment
The tokens used in the C program description example are shown below. #include "expand.h" extern void testb(void); extern void chgb(void); extern bit data1; extern bit data2; void main() { data1=1; data2=0; while(data1){ data1=data2; testb(); } if(data1&&data2){ chgb(); } } void lprintf(char *s,int i) { int j; char *ss; j=i; ss=s; } . . . lprintf............................................................. char, int......................................................... s, i ................................................................. * .................................................................... Identifier Keywords Identifiers Operator if.................................................................... && ................................................................. ( ) ................................................................. Keyword Operator Operator 1.................................................................... 0.................................................................... while.............................................................. { } ................................................................. =.................................................................... Constant Constant Keyword Delimiter Operator data1, data2.................................................. void ............................................................... Identifiers Keyword extern............................................................ Keyword
34
User's Manual U14872EJ1V0UM
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
2.1
Character Sets
(1) Character sets Character sets to be used in C programs include a source character set to be used to describe a source file and an execution character set to be interpreted in the execution environment. The value of each character in the execution character set is represented by JIS code. The following characters can be used in the source character set and execution character set: 26 uppercase letters ABCDE N O P Q R
F S
G T
H U
I V
J W
K X
L Y
M Z
26 lowercase letters abcde n o p q r
f s
g t
h u
i v
j w
k x
l y
m z
10 decimal numbers 01234 29 graphic characters !"#%& ; < = > ?
5
6
7
8
9
` [
( \
) ]
* ^
+ --
, {
|
. }
/ ~
:
and nonprintable control characters which indicate Space, Horizontal Tab, Vertical Tab, Form Feed, etc. (see escape sequences below.) Remark In character constants, string literal, and comment statements, characters other than above may also be used.
User's Manual U14872EJ1V0UM
35
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
(2) Escape sequences Nongraphic characters used for control characters as for alert, formfeed, and such are represented by escape sequences. Each escape sequence consists of the \ sign and an alphabetic character. Nongraphic characters represented by escape sequences are shown below. Table 2-1. List of Escape Sequences
Escape Sequence \a \b \f \n \r \t \v Meaning Alert Backspace Formfeed New Line Carriage Return Horizontal Tab Vertical Tab Character Code 07H 08H 0CH 0AH 0DH 09H 0BH
(3) Trigraph sequences When a source file includes a list of the three characters (called "trigraph sequence") shown in the left column of the table below, the list of the three characters is converted into the corresponding single character shown in the right column. Table 2-2. List of Trigraph Sequence
Trigraph Sequence ??= ??( ??/ ??) ??' ??< ??! ??> ??Meaning # [ \ ] ^ { | } ~
36
User's Manual U14872EJ1V0UM
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
2.2
Keywords
(1) ANSI-C keywords The following tokens are used by the C compiler as keywords and thus cannot be used as labels or variable names. auto default float short typedef break do goto signed union case double if sizeof unsigned char else int static void const enum long struct volatile continue extern register switch while for return
(2) Keywords added for the CC78K0S In this C compiler the following tokens have been added as keywords to implement its expanded functions. These tokens cannot be used as labels or variable names nor can ANSI (when an uppercase character is included, the token is not regarded as a keyword). Keywords which do not start with "_ _" can be made invalid by specifying the option (-ZA) that enables only ANSI-C language specification. callf, _ _callf, _ _banked 1 to 15, _ _rtos_interrupt, and _ _interrupt_brk are taken as keywords for compatibility with the CC78K0. _ _callt/callt ................................. _ _callf/callf ................................. _ _sreg/sreg...................................... noauto .................................................. _ _leaf/norec ................................... bit......................................................... _ _boolean/boolean......................... _ _interrupt...................................... _ _interrupt_brk ............................. _ _banked 1 to 15........................... _ _asm .................................................. _ _rtos_interrupt........................... _ _pascal ............................................ _ _directmap...................................... _ _temp ................................................ _ _mxcall ............................................ Declaration of callt function Declaration of callf function Declaration of sreg variable Declaration of noauto function Declaration of norec function Declaration of bit type variable Declaration of boolean type variable Hardware interrupt function Software interrupt function Bank function asm statement Interrupt handler for RTOS Pascal function Absolute address allocation specification Temporary variable _ _mxcall function
Note
Note Reserved keyword for interface with MX. This keyword must not be used by users.
User's Manual U14872EJ1V0UM
37
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
2.3
Identifiers
An identifier is the name given to a variable such as: Function Object Tag of structure, union, or enumeration type Member of structure, union, or enumeration type typedef name Label name Macro name Macro parameter Each identifier can consist of uppercase letters, lowercase letters, numeric characters, and the underscores. The following characters can be used as identifiers. There is no restriction for the maximum length of the identifier. In this compiler, however, only the first 249 characters can be identified (refer to Table 1-1 Maximum Performance Characteristics of this C Compiler). _(underscore) n A N 0 o B O 1 p C P 2 q D Q 3 a r E R 4 b s F S 5 c t G T 6 d u H U 7 e v I V 8 f w J W 9 g x K X h y L Y i z M Z j k l m
All identifiers must begin with other than a numerical character (namely, a letter or an underscore) and must not be the same as any keyword.
38
User's Manual U14872EJ1V0UM
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
2.3.1 Scope of identifiers The range within which the use of an identifier becomes effective is determined by the location at which the identifier is declared. The scope of identifiers is divided into the following four types. * Function scope * File scope * Block scope * Function prototype scope extern __boolean data1, data2; void testb (int x); void main(void) { int cot; data1=1; data2=0; while(data1){ data1=data2; j1: testb(cot); } } void testb(int x) { . . . (1) Function scope Function scope refers to the entirety within a function. An identifier with function scope can be referenced from anywhere within a specified function. Identifiers that have function scope are label names only. (2) File scope File scope refers to the entirety of a translation (compiling) unit. Identifiers that are declared outside a block or parameter list all have file scope. An identifier that has file scope can be referenced from anywhere within the program. x.................................................................... Block scope j1............................................................. Function scope cot................................................................. Block scope data1, data2 .................................................... File scope x............................................... Function prototype scope
User's Manual U14872EJ1V0UM
39
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
(3) Block scope Block scope refers to the range of a block (a sequence of declarations and statements enclosed by a pair of curly braces { } which begins with the opening brace and ends with the closing brace. Identifiers that are declared inside a block or parameter list all have block scope. An identifier that has block scope is valid until the innermost brace pair including the declaration of the identifier is closed. (4) Function prototype scope Function prototype scope refers to the range of a declared function from its beginning to the end. Identifiers that are declared inside a parameter list within a function prototype all have function prototype scope. An identifier that has function prototype scope is valid within a specified function. 2.3.2 Linkage of identifiers The linkage of identifiers refers to the situation whereby the same identifier declared more than once in different scopes or in the same scope can be referenced as the same object or function. By being linked, identifiers are regarded to be one and the same. Identifiers may be linked in the following three different ways: external linkage, internal linkage and no linkage (1) External linkage External linkage refers to identifiers to be linked in translation (compiling) units that constitute the entire program and as a collection of libraries. The following identifiers have external linkage examples: * The identifier of a function declared without storage class specification * The identifier of an object or function declared as extern, which has no storage class specification * The identifier of an object which has file scope but has no storage class specification. (2) Internal linkage Internal linkage refers to identifiers to be linked within one translation (compiling) unit. The following identifier has an internal linkage example: * The identifier of an object or function which has file scope and contains the storage class specifier static. (3) No linkage An identifier that has no linkage to any other identifier is an inherent entity. Examples of identifiers that have no linkage are as follows: * An identifier which does not refer to a data object or function * An identifier declared as a function parameter * The identifier of an object which does not have storage class specifier extern inside a block
40
User's Manual U14872EJ1V0UM
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
2.3.3 Name space for identifiers All identifiers are classified into the following "name spaces". * Label name ........................................................ Distinguished by a label declaration. * Tag name of structure, union, or enumeration... Distinguished by the keyword struct, union or enum * Member name of structure or union................... Distinguished by the dot (.) operator or arrow (->) operator. * Ordinary identifiers (other than above) .............. Declared as ordinary declarators or enumeration type constants. 2.3.4 Storage duration of objects Each object has a storage duration that determines its lifetime (how long it can remain in memory). This storage duration is divided into the following two categories: static storage duration and automatic storage duration (1) Static storage duration Before executing an object program that has a static duration, an area is reserved for objects and values to be stored are initialized once. The objects exist throughout the execution of the entire program and retain the values last stored. Objects that have a static storage duration are as follows. * Objects that have external linkage * Objects that have internal linkage * Objects declared by storage class specifier static (2) Automatic storage duration For objects that have automatic storage duration, an area is reserved when they enter a block to be declared. If initialization is specified, the objects are initialized as they enter from the beginning of the block. In this case, if any object enters the block by jumping to a label within the block, the object will not be initialized. For objects that have automatic storage duration, the reserved area will not be guaranteed after the execution of the declared block. Objects that have automatic storage duration are as follows. * Objects that have no linkage * Objects declared inside a block without storage class specifier static 2.3.5 Data types Data types determine the meaning of a value to be stored in each object and are divided into the following three categories. * Object type................................................... Type that indicates an object with size information * Function type ............................................... Type that indicates a function * Incomplete type ........................................... Type that indicates an object without size information The type categories are shown below.
User's Manual U14872EJ1V0UM
41
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
*
Basic types (Arithmetic types)
Integral types
char type Signed integral types signed char short int int long int Unsigned integral types (specified by unsigned) Enumeration type
Floating-point types
float double long double
*
Character types
char signed char unsigned char
* *
Incomplete types Derived types
Array with an indefinite object size, structure, union, and void type Array type Structure type Union type Function type Pointer type Aggregate type
*
Scalar types
Basic (Arithmetic types) Pointer type
(1) Basic types Basic data types are also referred to as "arithmetic types". The arithmetic types consist of integral types and floating-point types. (a) Integral types Integral data types are subdivided into four types. Each of these types has a value represented by the binary numbers 0 and 1. * char type * Signed integral type * Unsigned integral type * Enumeration type (i) char type The char type has a sufficient size to store any character in the basic execution character set. The value of a character to be stored in a char type object becomes positive. Data other than characters is handled as an unsigned integer. In this case, however, if an overflow occurs, the overflowed part will be ignored.
42
User's Manual U14872EJ1V0UM
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
(ii) Signed integral type The signed integral type is subdivided into the following four types: * signed char * short int * int * long int An object declared with the signed char type has an area of the same size as the char type without a qualifier. An int object without a qualifier has a size natural to the CPU architecture of the execution environment. A signed integral type data has its corresponding unsigned integral type data. Both share an area of the same size. The positive number of a signed integral type data is a subset of unsigned integral type data. (iii) Unsigned integral type The unsigned integral type is data defined with the unsigned keyword. No overflow occurs in any computation involving unsigned integral type data. The reason is that if the result of a computation involving unsigned integral type data becomes a value which cannot be represented by an integral type, the value will be divided by the maximum number which can be represented by an unsigned integral type plus 1 and substituted with the remainder in the result of the division. (iv) Enumeration type Enumeration is a collection or list of named integer constants. An enumeration type consists of one or more sets of enumeration. (b) Floating-point types The floating-point types are subdivided into the three types. * float * double * long double In this compiler, double and long double types as well as float type are supported as a floating-point expression for the single-precision normalized number that is specified in ANSI/IEEE 754-1985. Thus, float, double, and long double types have the same value range.
User's Manual U14872EJ1V0UM
43
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
Table 2-3. List of Basic Data Types
Type (signed) char unsigned char (signed) short int unsigned short int (signed) int unsigned int (signed) long int unsigned long int float double long double Value Range -128 to +127 0 to 255 -32768 to +32767 0 to 65535 -32768 to +32767 0 to 65535 -2147483648 to +2147483647 0 to 4294967295 1.17549435E-38F to 3.40282347E+38F 1.17549435E-38F to 3.40282347E+38F 1.17549435E-38F to 3.40282347E+38F
* The signed keyword can be omitted. However, with the char type, it is judged as signed char or unsigned char depending on the condition at compilation. * short int data and int data are handled as data which have the same value range but are of different types. * unsigned short int data and unsigned int data are handled as data which have the same value range but are of different types. * float, double, and long double data are handled as data which have the same value range but are of different types. (i) Floating-point number (float type) specifications * Format The floating-point number format is shown below.
(Higher address)
s 31 30
e 23 22
m 0
(Lower address)
The numerical values in this format are as follows.
(Value of sign) (-1) * (Value of mantissa) *2 (Value of exponent)
s: Sign (1 bit) 0 for a positive number and 1 for a negative number. e: Exponent (8 bits) An exponent with a base of 2 is expressed as a 1-byte integer (expressed by two's complement in the case of a negative), and used after having a further bias of 7FH added. relationships are shown in Table 2-4 below. These
44
User's Manual U14872EJ1V0UM
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
Table 2-4. Exponent Relationships
Exponent (Hexadecimal) FE
* * *
Value of Exponent 127
* * *
81 80 7F 7E
* * *
2 1 0 -1
* * *
01
-126
m: Mantissa (23 bits) The mantissa is expressed as an absolute value, with bit positions 22 to 0 equivalent to the 1st to 23rd places of a binary number. Except for when the value of the floating point is 0, the value of the exponent is always adjusted so that the mantissa is within the range of 1 to 2 (normalization). The result is that the position of 1 (i.e. the value of 1) is always 1, and is thus represented by omission in this format. * Zero expression When exponent = 0 and mantissa = 0, 0 is expressed as follows.
(Value of sign) (-1) *0
* Infinity expression When exponent = FFH and mantissa = 0, is expressed as follows.
(Value of sign) (-1) *
* Unnormalized value When exponent = 0 and mantissa 0, the unnormalized value is expressed as follows.
(Value of sign) (-1) * (Value of mantissa) *2 -126
Remark
The mantissa value here is a number less than 1, so bit positions 22 to 0 of the mantissa express as is the 1st to 23rd decimal places.
* Not-a-number (NaN) expression When exponent = FFH and mantissa 0, NaN is expressed, regardless of the sign. * Operation result rounding Numerical values are rounded down to the nearest even number. If the operation result cannot be expressed in the above floating-point format, round to the nearest expressible number. If there are two values that can express the differential of the prerounded value, round to an even number (a number whose lowest binary bit is 0).
User's Manual U14872EJ1V0UM
45
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
* Operation exceptions There are five types of operation exceptions, as shown below. Table 2-5. List of Operation Exceptions
Exception Underflow Inexact Overflow Zero division Operation impossible Return Value Unnormalized number 0 Not-a-number (NaN)
Calling the matherr function causes a warning to appear when an exception occurs. (2) Character types The character data types include the following three types. * char * signed char * unsigned char (3) Incomplete types The incomplete data types include the following four types. * Arrays with indefinite object size * Structures * Unions * void type (4) Derived types The derived types are divided into the following three categories. * Array type * Structure type * Union type * Function type * Pointer type (a) Aggregate type The aggregate type is subdivided into two types. Array type and Structure type. An aggregate type data is a collection of member objects to be taken successively.
46
User's Manual U14872EJ1V0UM
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
(i)
Array type The array type continuously allocates a collection of member objects called the element type. Member objects all have an area of the same size. The array type specifies the number of element types and the elements of the array. It cannot create the array of incomplete type.
(ii) Structure type The structure type continuously allocates member objects each differing in size. Giving it a name can specify each member object. (b) Union type The union type is a collection of member objects that overlap each other in memory. These member objects differ in size and name and can be specified individually. (c) Function type The function type represents a function that has a specified return value. A function type data specifies the type of return value, the number of parameters, and the type of parameter. If the type of return value is T, the function is referred to as a function that returns T. (d) Pointer type The pointer type is created from a function type object type called a referenced type as well as from an incomplete type. The pointer type represents an object. The value indicated by the object is used to reference the entity of a referenced type. A pointer type data created from the referenced type T is called a pointer to T. (5) Scalar types The arithmetic types (basic type) and pointer type are collectively called the scalar types. The scalar types include the following data types: * char type * Signed integral type * Unsigned integral type * Enumeration type * Floating-point type * Pointer type
User's Manual U14872EJ1V0UM
47
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
2.3.6 Compatible type and composite type (1) Compatible type If two types are the same, they are said to be compatible or have compatibility. For example, if two structures, unions, or enumeration types that are declared in separate translation (compiling) units have the same number of members, the same member name and compatible member types, they have a compatible type. In this case, the individual members of the two structures or unions must be in the same order and the individual members (enumerated constants) of the two enumerated types must have the same values. All declarations related to the same objects or functions must have a compatible type. (2) Composite type A composite type is created from two compatible types. The following rules apply to the composite type. * If either of the two types is an array of known type size, the composite type is an array of that size. * If only one of the types is a function type with a parameter type list (declared with a prototype), the composite type is a function prototype with a parameter type list. * If both types have a parameter type list (i.e., functions with prototypes), the composite type is the one with a prototype consisting of all information that can be combined from the two prototypes. [Example of composite type] Assume that two declarations that have file scope are as follows. int f(int(*)(),double(*)[3]); int f(int(*)(char *),double(*)[]); The composite type of the function in this case becomes as follows. int f(int(*)(char *),double(*)[3]);
48
User's Manual U14872EJ1V0UM
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
2.4
Constants
A constant is a variable that does not change in value during the execution of the program, and its value must be set beforehand. A type for each constant is determined according to the format and value specified for the constant. The following four constant types are available. * Floating-point constants * Integer constants * Enumeration constants * Character constants 2.4.1 Floating-point constant A floating-point constant consists of a valid digit part, exponent part, and floating-point suffix. Valid digit part: Exponent part: Integer part, decimal point, and fraction part e or E, signed exponent I/L (long double) If omitted (double) The signed exponent of the exponent part and the floating-point suffix can be omitted. Either the integer part or fraction part must be included in the valid digits. Also, either the decimal point or exponent part must be included (example: 1.23F, 2e3). 2.4.2 Integer constant An integer constant starts with a number and does not have the decimal point or the exponent part. An unsigned suffix can be added after the integer constant to indicate that the integer constant is unsigned. A long suffix can be added after the integer constant to indicate that the integer constant is long. There are the following three types of integer constant. * Decimal constant: Decimal number that starts with a number other than 0 Decimal number = 123456789 * Octal constant: Integer suffix 0 + octal number Octal number = 01234567 * Hexadecimal constant: Integer suffix 0x or 0X + hexadecimal number Hexadecimal number = 0123456789 abcdef ABCDEF Unsigned suffix uU Long suffix lL (1) Decimal constant A decimal constant is an integer value with a base (radix) of 10 and must begin with a number other than 0 followed by any numbers 0 through 9 (example: 56U).
Floating point suffix: f/F (float)
User's Manual U14872EJ1V0UM
49
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
(2) Octal constant An octal constant is an integer value with a base of 8 and must begin with 0 followed by any numbers 0 through 7 (example: 034U). (3) Hexadecimal constant A hexadecimal constant is an integer value with a base of 16 and must begin with 0x or 0X followed by any numbers 0 through 9 and a through f or A through F which represent 10 through 15 (example: 0xF3). The type of integer constant is regarded as the first of the "representable type" shown below. In this compiler, the type of the unsubscripted constant can be changed to char or unsigned char depending on the compile condition (option). (Integer constant) (Representable type)
* Unsuffixed decimal number.................................. int, long int, unsigned long int * Unsuffixed octal, hexadecimal number ................ int, unsigned int, long int, unsigned long int * Suffixed u or U...................................................... unsigned int, unsigned long int * Suffixed l or L ....................................................... long int, unsigned long int * Suffixed u or U, and suffixed l or L ....................... unsigned long int 2.4.3 Enumeration constants Enumeration constants are used for indicating an element of an enumeration type variable, that is, the value of an enumeration type variable that can have only the specific value indicated by an identifier. The enumeration type (enum) is whichever is the first type from the top of the list of three types shown below that can represent all the enumeration constants. The enumeration constant is indicated by the identifier. * signed char * unsigned char * signed int It is described as `enum enumeration type {list of enumeration constant}'. Example enum months{January=1,February,March,April,May}; When the integer is specified with =, the enumeration variable has the integer value, and the following value of enumeration variable has that integer value + 1. In the example shown above, the enumeration variable has 1, 2, 3, 4, 5, respectively. When there is not `= 1', each constant has 0, 1, 2, 3, 4, 5, respectively.
50
User's Manual U14872EJ1V0UM
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
2.4.4 Character constants A character constant is one or more character strings enclosed in a pair of single quotes as in `X' or `ab'. A character constant does not include single quote ('), backslash ( or \), and line feed character (n). To represent these characters, escape sequences are used. There are the following three types of escape sequences. * Simple escape sequence: * Octal escape sequence: * Hexadecimal escape sequence: \' \a \" \b \? \f \ \n
Note 1
\r )
\t
\v
\octal number [octal number octal number] (example: \012, \0 (example: \xFF
Note 2
\x hexadecimal number )
Notes 1. Null character 2. In this compiler, \xFF represents -1. If the condition (option) that regards char as unsigned char is added, however, it represents +255.
2.5
String Literal
A string literal is a string of zero or more characters enclosed in a pair of double quotes as in "xxx" (example: "xyz"). A single quote (') is represented by the single quotation mark itself or by escape sequence \', whereas a double quote (") is represented by escape sequence \". Array elements have char type string literal and are initialized by tokens given (example: char array [ ] = "abc";).
2.6
Operators
The operators are shown below. [] ++ / ^ ? = &= , () -% | : *= ^= # /= |= ## %= += -= <<= >>= . & << && -> * >> || + < - > ~ <= ! >= sizeof == !=
The [ ], ( ), and ?: operators must always be used in pairs. An expression may be described in brackets "[ ]", in parentheses "( )", or between "?" and ":". The # and ## operators are used only for defining macros in preprocessing directives. (For the description, refer to CHAPTER 5 OPERATORS AND EXPRESSIONS.)
User's Manual U14872EJ1V0UM
51
CHAPTER 2
CONSTRUCTS OF C LANGUAGE
2.7 Delimiters
A delimiter is a symbol that has an independent syntax or meaning. However, it never generates a value. The following delimiters are available for use in C. [] () {} * , : = ; ... #
An expression declaration or statement may be described in brackets "[ ]", parentheses "( )", or braces "{ }". These delimiters must always be used in pairs as shown above. The delimiter # is used only for preprocessing directives.
2.8
Header Name
The header name indicates the name of an external source file. This name is used only in the preprocessing directive "#include". An example of an #include instruction of a header name is shown below. For the details of each #include instruction, refer to 9.2 Source File Inclusion Directive. #include
#include "header name"
2.9
Comment
A comment refers to a statement to be included in a C source module for information only. It begins with "/*" and ends with "*/". The part after "//" to the line feed can be identified as a comment statement by the -ZP option. Example /* comment statement */ //comment statement
52
User's Manual U14872EJ1V0UM
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
This chapter explains how data (variables) or functions to be used in C should be declared as well as the scope for each data or function. A declaration means the specification of an interpretation or attribute for an identifier or a collection of identifiers. A declaration to reserve a storage area for an object or function named by an identifier is referred to as a "definition". An example of a declaration is shown below. #define TRUE #define SIZE 1 200
#define FALSE 0
void main(void) { auto int i,prime,k; for(i=0;i<=SIZE;i++) mark[i]=TRUE; . . . A declaration consists of a storage class specifier, type specifier, initialize declarator, etc. The storage class specifier and type specifier specify the linkage, storage duration, and the type of entity indicated by the declarator. An initialize declarator list is a list of declarators each delimited with a comma. Each declarator may have additional type information or an initializer or both. If an identifier for an object declares that it has no linkage, the type for the object must be perfect (the object with information related to the size) at the end of the declarator or initialize declarator (if there is any). /* declaration of automatic variables */
User's Manual U14872EJ1V0UM
53
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
3.1
Storage Class Specifiers
A storage class specifier specifies the storage class of an object. It indicates the storage location of the value that the object has, and the scope of the object. In a declaration, only one storage class specifier can be described. The following five storage class specifiers are available. * typedef * extern * static * auto * register
(1) typedef The typedef specifier declares a synonym for the specified type. See 3.6 typedef for details of the typedef specifier. (2) extern The extern specifier indicates (tells the compiler) that a variable immediately before this specifier is declared elsewhere in the program (i.e., an external variable). (3) static The static specifier indicates that an object has static storage duration. For an object that has static storage duration, an area is reserved before the program execution and the value to be stored is initialized only once. The object exists throughout the execution of the entire program and retains the value last stored in it. (4) auto The auto specifier indicates that an object has automatic storage duration. For an object that has automatic storage duration, an area is reserved when the object enters a block to be declared. At entry into the declared block from its top, the object is initialized if so specified. If the object enters the block by jumping to a label within the block, the object will not be initialized. The area reserved for an object with automatic storage duration will not be guaranteed after the execution of the declared block. (5) register The register specifier indicates that an object is assigned to a register of the CPU. With this C compiler, it is allocated to the register or saddr area of the CPU. See CHAPTER 11 EXTENDED FUNCTIONS for details of register variables.
54
User's Manual U14872EJ1V0UM
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
3.2
Type Specifiers
A type specifier specifies (or refers to) the type of an object. The following type specifiers are available. * void * char * short * int * long * float * double * long double * signed * unsigned * Structure or union specifier * Enumeration specifier * typedef name
In this C compiler, the following type specifiers have been added. * bit/boolean/_ _boolean
User's Manual U14872EJ1V0UM
55
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
The following is an explanation of the meaning of each type specifier and the limit values that can be expressed with this compiler (the values enclosed in the parentheses). Since this compiler supports only the single precision of IEEE Std 754-1985 for floating-point operations, double and long double data are regarded as having the same format as float data. * void .................................................................... Collection of null values * char .................................................................... Size of the basic character set that can be stored * signed char ..................................................... Signed integer (-128 to +127) * unsigned char ................................................. Unsigned integer (0 to 255) * short, signed short, short int, signed short int........................................... Signed integer (-32768 to +32767) * unsigned short, unsigned short int .... Unsigned integer (0 to 65535) * int, signed, signed int............................ Signed integer (-32768 to +32767) * unsigned, unsigned int.............................. Unsigned integer (0 to 65535) * long, signed long, long int, signed long int............................................. Signed integer (-2147483648 to +2147483647) * unsigned long, unsigned long int ........ Unsigned integer (0 to 4294967295) * float .................................................................. Single-precision floating-point number (1.17549435E-38F to 3.40282347E+38F) * double ................................................................ Double-precision floating-point number (1.17549435E-38F to 3.40282347E+38F) * long double ..................................................... Extended precision floating point number (1.17549435E-38F to 3.40282347E+38F) * Structure/union specifier ...................................... Collection of member objects * Enumeration specifier .......................................... Collection of int type constants * typedef name .................................................... Synonym of specified type * bit, boolean, _ _boolean.......................... Integers represented with a single bit (0 to 1)
Type specifiers separated from each other with a slash have the same size.
56
User's Manual U14872EJ1V0UM
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
3.2.1 Structure specifier and union specifier Both the structure specifier and union specifier indicate a collection of named members (objects). These member objects can have different types from one another. (1) Structure specifier The structure specifier declares a collection of two or more different types of variables as one object. Each type of object is called a member and can be given a name. For members, continuous areas are reserved in the order of their declarations. However, because the 78K/0S Series contains a restriction whereby word data is unable to be read from or written to odd addresses, the code size is prioritized by default, and align data is inserted to ensure members of 2 bytes or more are allocated to even addresses. Gaps may therefore occur between members due to the align data. The -RC option can be specified to inhibit insertion of align data and enable structures to be packed. In this case, although the size of the data is reduced, members of 2 or more bytes allocated to odd addresses are read/written using 1-byte unit read/write code, which increases the code size. The structure is declared as follows. The declaration will not yet allocate memory since it does not have a list of structure variables. For the definition of the structure variables, refer to CHAPTER 7 STRUCTURES AND UNIONS. struct identifier {member declaration list};
Example of structure declaration struct tnode{ int count; struct tnode *left,*right; };
(2) Union specifier The union specifier declares a collection of two or more different types of variables as one object. Each type of object is called a member and can be given a name. The members of a union overlay each other in area, namely, they share the same area. The union is declared as follows. The declaration will not yet allocate memory since it does not have a list of union variables. For the definition of the union variables, refer to CHAPTER 7 STRUCTURES AND UNIONS. union identifier {member declaration list};
Example of union declaration union u_tag{ int var1 ; long var2 ; };
Each member object can be any type other than the incomplete types or function types. The member can be declared with the number of bits specified. The member with the number of bits specified is called a bit field.
User's Manual U14872EJ1V0UM
57
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
In this compiler, extended functions related to bit field declaration have been added. For details, refer to 11.5 (14) Bit field declaration. (3) Bit field A bit field is an integral type area consisting of a specified number of bits. For the bit field, int type, unsigned int type, and signed int type data can be specified. signed int field will be judged as a sign bit.
Note 2 Note 1
The MSB of an int field which has no qualifier or a
If two or more bit fields exist, the second and subsequent bit fields are packed into the adjacent bit positions, provided there is sufficient space within the same memory unit. By placing an unnamed bit field with a width of 0, the next bit field will not be packed into a space within the same memory unit. An unnamed bit field has no declarator and declares a colon and a width only. Unary&operator (address) cannot be applied to the bit field object. Notes 1. In this compiler, char type, unsigned char type, and signed char type can also be specified. All of them are regarded as unsigned type since this compiler does not support signed type bit field. 2. In this compiler, the direction of bit field allocation can be changed by compiler option -RB (for details, refer to CHAPTER 11 EXTENDED FUNCTIONS). The following shows an example of a bit field. struct data{ unsigned int a:2; unsigned int b:3; unsigned int c:1; }no1;
58
User's Manual U14872EJ1V0UM
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
3.2.2 Enumeration specifiers An enumeration type specifier indicates a list of objects to be put in sequence. Objects to be declared with the enum specifier will be declared as constants that have int types. The enumeration specifier is declared as shown below. enum identifier {enumerator list}
Objects are declared with an enumerator list. Values are defined for all objects in the list in the order of their declaration by assigning the value of 0 to the first object and the value of the previous object plus 1 to the 2nd and subsequent objects. A constant value may also be specified with "=". In the following example, "hue" is assumed as the tag name of the enumeration, "col" as an object that has this (enum) type, and "cp" as a pointer to an object of this type. In this declaration, the values of the enumeration become "{0, 1, 20, 21}". enum hue{ chartreuse, burgundy, claret=20, winedark }; enum hue col,*cp; void main(void) { col=claret; cp=&col ; /*...*/ (*cp!=burgundy) /*...*/ . . .
User's Manual U14872EJ1V0UM
59
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
3.2.3 Tags A tag is a name given to a structure, union, or enumeration type. A tag has a declared data type and objects of the same type can be declared with a tag. The identifier in the following declaration is a tag name. structure/union identifier {member declaration list}
or enum identifier {enumerator list}
A tag contains the contents of the structure/union or enumeration defined by a member.
In the next and
subsequent declarations, the structure of a struct, union, or enum type becomes the same as that of the tag's list. In the subsequent declarations within the same scope, the list enclosed in braces must be omitted. The following type specifier is undefined with respect to its contents and thus the structure or union has an incomplete type. structure/union identifier
A tag to specify the type of this type specifier can be used only when the object size is unnecessary. The reason is that by defining the contents of the tag within the same scope, the type specification becomes incomplete. In the following example, the tag "tnode" specifies a structure that includes pointers to an integer and two objects of the same type. struct tnode{ int count; struct tnode *left,*right; };
The next example declares "s" as an object of the type indicated by the tag (tnode) and "sp" as a pointer to the object of the type indicated by the tag. By this declaration, the expression "sp left" indicates a pointer to "struct tnode" on the left of the object pointed to by "sp" and the expression "s.right count" indicates "count" which is a member of "struct tnode" on the right of "s". typedef struct tnode TNODE; struct tnode{ int count; struct tnode *left,*right; }; TNODE s *sp; void main(void){ sp->left=sp->right; s.right->count=2; }
60
User's Manual U14872EJ1V0UM
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
3.3
Type Qualifiers
Two type qualifiers are available: const and volatile. These type qualifiers affect left-side values only. Using a left-side value that has non-const type qualifier cannot change an object that has been defined with const type qualifier. Using a left-side value that has non-volatile type qualifier cannot reference an object that has been defined with volatile type qualifier. An object that has volatile qualifier type can be changed by a method not recognizable by the compiler or may have other unnoticeable side effects. Therefore, an expression that references this object must be strictly evaluated according to the sequence rules that regulate abstractly how programs written in C should be executed. In addition, the values to be last stored in the object at every sequence point must be in agreement with those determined by the program except the changes due to the factors unrecognizable by the compiler as mentioned above. If an array type is specified with type qualifiers, the qualifiers apply to the array members, not the array itself. No type qualifier can be included in the specification of a function type. However, callt, _ _ callt, callf, _ _ callf, noauto, norec, _ _ leaf, _ _ interrupt, _ _ interrupt_brk, _ _rtos_interrupt, _ _pascal, which are the type qualifiers unique to this compiler mentioned in 2.2 Keywords, can be included as type qualifiers. sreg, _ _sreg, _ _directmap, and _ _temp are also type qualifiers. In the following example, "real_time_clock" can be changed by hardware, but operations such as assignment, increment, and decrement are not allowed. extern const volatile int real_time_clock;
An example of modifying aggregate type data with type qualifiers is shown below. const struct s{int mem;} cs={1}; struct s ncs; /* object ncs is changeable */ /* array of const int array */ typedef int A[2][3]; const A a={{4,5,6},{7,8,9}}; int *pi; const int *pci; ncs=cs; cs=ncs; pi=&ncs.mem; pi=&cs.mem; pci=&cs.mem; pi=a[0]; /* correct */ /* violates restriction of Lvalue which has modifiable assignment operator */ /* correct */ /* violates restriction of the type of assignment operator = */ /* correct */ /* incorrect:a[0] has "const int *" type */
User's Manual U14872EJ1V0UM
61
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
3.4
Declarators
A declarator declares an identifier. Here, pointer declarators, array declarators, and function declarators are mainly discussed. The scope of an identifier and a function or object which has a storage duration and a type are determined by declarators. A description of each declarator is provided below. 3.4.1 Pointer declarators A pointer declarator indicates that an identifier to be declared is a pointer. A pointer points to (indicates) the location where a value is stored. Pointer declarations are performed as follows. * type qualifier list identifier
By this declaration, the identifier becomes a pointer to T1. The following two declarations indicate a variable pointer to a constant value and an invariable pointer to a variable value, respectively. const int *ptr_to_constant; int *const constant_ptr;
The first declaration indicates that the value of the constant "const int" pointed by the pointer "ptr_to_constant" cannot be changed, but the pointer "ptr_to_constant" itself may be changed to point to another "const int". Likewise, the second declaration indicates that the value of the variable "int" pointed by the pointer "constant_ptr" may be changed, but the pointer "constant_ptr" itself must always point to the same position. The declaration of the invariable pointer "constant_ptr" can be made distinct by including a definition for the pointer type to the int type data. The following example declares "constant_ptr" as an object that has a const qualifier pointer type to int. typedef int *int_ptr; const int_ptr constant_ptr;
62
User's Manual U14872EJ1V0UM
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
3.4.2 Array declarators An array declarator declares to the compiler that an identifier to be declared is an object that has an array type. Array declaration is performed as shown below. type identifier [constant expression]
By this declaration, the identifier becomes an array that has the declared type.
The value of the constant
expression becomes the number of elements in the array. The constant expression must be an integer constant expression which has a value greater than 0. In the declaration of an array, if a constant expression is not specified, the array becomes an incomplete type. In the following example, a char type array "a[ ]" which consists of 11 elements and a char type pointer array "ap[ ]" which consists of 17 elements have been declared. char a[11],*ap[17];
In the following two examples of declarations, "x" in the first declaration specifies a pointer to an int type data and "y" in the second declaration specifies an array to an int type data which has no size specification and is to be declared elsewhere in the program. extern int *x; extern int y[];
3.4.3 Function declarators (including prototype declarations) A function declarator declares the type of return value, argument, and the type of the argument value of a function to be referenced. Function declaration is performed as follows. type identifier (parameter list or identifier list)
By this declaration, the identifier becomes a function which has the parameter specified by the parameter type list and returns the value of the type declared before the identifier. Parameters of a function are specified by a parameter identifier lists. By these lists, an identifier, which indicates argument and its type, are specified. A macro defined in the header file "stdarg.h" converts the list described by the ellipsis (, ...) into parameters. For a function that has no parameter specification, the parameter list will become "void".
User's Manual U14872EJ1V0UM
63
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
3.5
Type Names
A type name is the name of the data type that indicates the size of a function or object. Syntax-wise, it is a function or object declaration less identifiers. Examples of type names are given below. * int ................................................... Specifies an int type. * int *................................................. Specifies a pointer to an int type. * int *[3]............................................. Specifies an array which has three pointers to an int type. * int (*) [3] ......................................... Specifies a pointer to an array which has three int types. * int *( ) ............................................ Specifies a function which returns a pointer to an int type which has no parameter specification. * int (*) (void) .................................... Specifies a pointer to a function which returns an int type which no parameter specification. * int (*const [ ]) (unsigned int, ...) ... Specifies an indefinite number of arrays which have one parameter of unsigned int type and an invariable pointer to each function that returns an int type.
64
User's Manual U14872EJ1V0UM
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
3.6
typedef Declarations
The defined identifier
The typedef keyword defines that an identifier is synonymous with a specified type. becomes a typedef name. The syntax of typedef names is shown below. typedef type identifier;
In the following example, "distance" is an int type, the type of "metricp" is a pointer to a function that returns an int type that has no parameter specification, the type of "z" is a specified structure, and "zp" is a pointer to this structure. typedef int MILES,KLICKSP(); typedef struct{long re,im} complex; /*...*/ MILES distance; extern KLICKSP *metricp; complex z,*zp;
In the following example, typedef name t is declared with signed int type, and typedef name plain is declared with int type, respectively, and the structure with three bit field members is declared. The bit field members are as follows. * Bit field member with name t and the value 0 to 15 * Bit field member without a name and the const qualified value -16 to +15 (if accessed) * Bit field member with name r and the value -16 to +15 typedef signed int t; typedef int plain; struct tag{ unsigned t:4; const t:5; plain r:5; };
In this example, these two bit field declarations differ in the point that the first bit field declaration has unsigned as the type specifier (therefore, t becomes the name of the structure member), and the second bit field declaration, has const as the type qualifier (qualifiers t which can be referred to as typedef name). After this declaration, if: t f(t(t)); long t;
is found within the valid range, the function f is declared as "function which has one parameter and returns signed int", and the parameter is declared as "pointer type for the function which has one parameter and returns signed int". The identifier t is declared as long type.
User's Manual U14872EJ1V0UM
65
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
typedef names may be used to facilitate program reading. For example, the following three declarations for the function signal all specify the same type as the first declaration that does not use typedef. typedef void fv(int); typedef void (*pfv)(int); void(*signal(int,void(*)(int)))(int); fv *signal(int,fv *); pfv signal(int,pfv);
66
User's Manual U14872EJ1V0UM
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
3.7
Initialization
Initialization refers to setting a value in an object beforehand. Initializers carry out the initialization of an object. Initialization is performed as follows. object = {initializer list}
An initializer list must contain initializers for the number of objects to be initialized. All expressions in initializers or an initializer list for objects that have static storage duration and objects that have an aggregate type or a union type must be specified with constant expressions. Identifiers that declare block scope but have external or internal linkage cannot be initialized. (1) Initialization of objects which have a static storage duration If no attempt is made to initialize an arithmetic type object that has static storage duration, the value of the object will be implicitly initialized to 0. Likewise, a pointer type object which has a static storage duration will be initialized to a null pointer constant. Example unsigned int gval1; static int gval2; void func(void){ static char aval; } /* initialized by 0 */ /* initialized by 0 */ /* initialized by 0 */
(2) Initialization of objects which have an automatic storage duration The value of an object which has an automatic storage duration becomes indefinite and will not be guaranteed if it is not initialized. Example void func(void){ char aval; . . . aval=1; } /* initialized to 1 */ /*undefined at this point */
(3) Initialization of character arrays A character array can be initialized with a character string literal (character string enclosed in " "). Likewise, a character string in which a series of character string literals are contained initializes the individual members or elements of an array. In the following example, the array objects "s" and "t" with no type qualifier are defined and the elements of each array will be initialized by character string literal. char s[]="abc",t[3]="abc";
The next example is the same as the above example of array initialization.
User's Manual U14872EJ1V0UM
67
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
char s[]={'a','b','c','\0'}, t[]={'a','b','c'};
The next example defines p as "pointer to char" type and the member is initialized by character string literal so that the length indicates a "char array" type object. char *p="abc";
(4) Initialization of aggregate or union type objects * Aggregate type An aggregate type object is initialized with a list of initializers described in ascending order of subscripts or members. The initializer list to be specified must be enclosed in braces. If the number of initializers in the list is less than the number of aggregate members, the members not covered by the initializers will be implicitly initialized just the same as an object which has a static storage duration. With an array of unknown size, the number of elements is governed by the number of initializers and the array will no longer become an incomplete type. * Union type A union type object is initialized of initializer for the first member of the union that is enclosed in braces. In the following example, the array "x" of unknown size will change to a one-dimensional array that has three elements as a result of its initialization. int x[]={1,3,5};
The next example shows a complete definition which has initializers enclosed in braces. "{1, 3, 5}" initializes "y [0] [0]", "y [0] [1]", and "y [0] [2]" in the 1st line of the array object "y[0]". Likewise, in the second line, the elements of the array objects "y [1]" and "y [2]" are initialized. The initial value of "y[3]" is 0 since it is not specified. char y[4][3]={ {1,3,5}, {2,4,6}, {3,5,7}, }; The next example produces the same result as the above example. char z[4][3]={ 1,3,5,2,4,6,3,5,7 };
In the following example, the elements in the first row of "z" are initialized to the specified values and the rest of the elements are initialized to 0.
68
User's Manual U14872EJ1V0UM
CHAPTER 3
DECLARATION OF TYPES AND STORAGE CLASSES
char z[4][3] = { {1}, {2}, {3}, {4} };
In the next example, a three-dimensional array is initialized. q[0] [0] [0] are initialized to 1, q[1] [0] [0] to 2, and q[1] [0] [1] to 3. 4, 5 and 6 initialize q[2] [0] [0], q[2] [0] [1], and q[2] [1] [0], respectively. The rest of the elements are all initialized to 0. short q[4][3][2] = { {1}, {2, 3} {4, 5, 6} };
The following example produces the same result as the above initialization of the three-dimensional array. short q[4][3][2] = { 1, 0, 0, 0, 0, 0, 2, 3, 0, 0, 0, 0, 4, 5, 6 };
The following example shows a complete definition of the above initialization using braces. Short q[4][3][2] = { { {1}, }, { {2, 3}, }, { {4, 5, 6}, } };
User's Manual U14872EJ1V0UM
69
CHAPTER 4
TYPE CONVERSIONS
In an expression, if two operands differ in data type, the compiler automatically performs a type conversion operation. This conversion is similar to the change obtained by the cast operator. This automatic type conversion is called an implicit type conversion. In this chapter, this implicit type conversion is explained. Type conversion operations include usual arithmetic conversions, conversions involving truncation/round off, and conversions involving sign change. A list of conversions between types is shown in Table 4-1.
70
User's Manual U14872EJ1V0UM
CHAPTER 4
TYPE CONVERSIONS
Table 4-1. List of Conversions Between Types
After Conversion (signed) unsigned (signed) char char short int Before Conversion (signed) char + - unsigned char (signed) short int + - unsigned short int (signed) int + - unsigned int (signed) long int + - unsigned long int float double long double N N N N N N N N N N N
unsigned (signed) unsigned (signed) unsigned float double long short int int int long int long int double
Remarks 1. The signed keyword can be omitted. However, with a char type data, the data type is regarded as the signed char or unsigned char type depending on the compile-time condition (option). 2. Conventions : \: N: : Type conversion will be performed properly. Type conversion will not be performed. A correct value will not be generated. (The data type will be regarded as an unsigned int type.) The data type will not change bit-image-wise. However, if a positive number cannot represent it sufficiently, no correct value will be generated (regarded as an unsigned integer) Blank:An overflow in the result of the conversion will be truncated. The + or - sign of the data may be changed depending on the type after the conversion.
User's Manual U14872EJ1V0UM
71
CHAPTER 4
TYPE CONVERSIONS
4.1
Arithmetic Operands
(1) Characters and integers (general integral promotion) The data types of char, short int, and int bit fields (whether they are signed or unsigned) or of objects that have an enumeration type will be converted to int types if their values are within the range that can be represented with int types. If not within the range, they will be converted to unsigned int types. These implicit type conversions are referred to as "general integral general promotion". changed by this general integral promotion. General integral promotion will retain the value of the original data type including its sign. char type data without a type qualifier will normally be handled as signed char in this compiler. It can be handled as an unsigned char using an option. (2) Signed integers and unsigned integers When a value with an integer type is converted to another, the value will not be changed if the value can be expressed with the integer type after conversion. When a signed integer is converted to an unsigned integer of the same or larger size, the value is not changed unless the value of the signed integer is negative. If the value of the signed integer is negative and the unsigned integer has a size larger than that of the signed integer, the signed integer is expanded to the signed integer with the same size as the unsigned integer, and then it is added with the value equal to the maximum number that can be expressed with the unsigned integer plus 1, and the signed integer before conversion is converted to the unsigned value. When a value with an integer type is converted to an unsigned integer with a smaller size, the conversion result is a non-negative remainder which the value is divided with that value which 1 is added to the maximum number that can be expressed with an unsigned integer after conversion. When a value with an integer type is For the converted to a signed integer with smaller size or when an unsigned integer is converted to a signed integer with the same size, the overflown value is ignored if the value after conversion cannot be expressed. conversion pattern, refer to Table 4-1. List of Conversions Between Types. Conversion operations from signed integral type to unsigned integral type are as listed in Table 4-2 below. Table 4-2. Conversions from Signed Integral Type to Unsigned Integral Type
unsigned Smaller in Value Range + signed - / + / Greater in Value Range
All other arithmetic types will not be
:Type conversion will be performed properly. +: The data will be converted to a positive integer. /: The result of the conversion will be the remainder of the integer value, modulo the largest possible value of the type to be converted plus 1.
72
User's Manual U14872EJ1V0UM
CHAPTER 4
TYPE CONVERSIONS
(3) Usual arithmetic type conversions Types obtained as a result of operations on arithmetic type data will have a wide range of values. The type conversion of the operation result is performed as follows. * If either one of the operands has long double type, the other operand is converted to long double type. * If either one of the operands has double type, the other operand is converted to double type. * If either one of the operands has float type, the other operand is converted to float type. In cases other than above, general integer expansion is performed for both operands according to the following rules. Figure 4-1 shows the rules. Figure 4-1. Usual Arithmetic Type Conversions
unsigned long int ......................... If either of the two operands is unsigned long int type, or with one operand being long int type and the other being unsigned int type, if the value of unsigned int type cannot represented by long int type, both operands will be converted to unsigned long int type. long int ......................... In cases other than above, if one operand is long int type and if the value of the other operand can be represented by long int type, the other operand will be converted to long int type. ......................... In cases other than above, if one operand is unsigned int type, the other operand will be converted to unsigned int type. int ......................... In cases other than above, both operands will have int type.
unsigned int
In this compiler, the conversion to int type can be intentionally disabled by compile condition (optimizing option) (For the details, refer to CC78K0S C Compiler Operation (U14871E) CHAPTER 5 COMPILER OPTION).
User's Manual U14872EJ1V0UM
73
CHAPTER 4
TYPE CONVERSIONS
4.2
Other Operands
(1) Left-side values and function locators A left-side value refers to an expression that specifies an object (and has an incomplete type other than object type or void type). Left-side values that do not have array types, incomplete types, or const qualifier types, and structures or unions which have no const qualifier type members are "modifiable left-side values". A left-side value which has no array type will be converted to a value stored in the object to be specified, except when it is the operand of the sizeof operator, unary & operator, ++ operator, or - - operator or the left operand of an operator or an assignment operator. By being converted, it will no longer serve as a left-side value. The behavior of left-side values that have incomplete types but no array types will not be guaranteed. A left-side value which has an "... array" type except character arrays will be converted to an expression which has a "pointer to ..." type. This expression is no longer a left-side value. A function locator is an expression that has a function type. With the exception of the operand of the sizeof operator or unary & operator, a function locator that has a "function type that returns ..." will be converted to an expression that has a "pointer type to a function that returns ...". (2) void The value (non-existent) of a void expression (i.e., an expression that has the void type) cannot be used in any way. Neither implicit nor explicit conversion to exclude void will be applied to this expression. If an expression of another type appears in the context which requires a void expression, the value of the expression or specifier is assumed to be non-existent. (3) Pointers A void pointer can be converted to a pointer to any incomplete type or object type. Conversely, a pointer to any incomplete type or object type can be converted to a void pointer. In either case, the result value must be equal to that of the original pointer. An integer constant expression which has the value of 0 and has been cast to the void * type is referred to as a "null pointer constant". If the null pointer constant is substituted with, equal to, or compared with some pointer, the null pointer constant will be converted to that pointer.
74
User's Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
This chapter describes the operators and expressions to be used in the C language. C has an abundance of operators for arithmetic, logical, and other operations. This rich set of operators also includes those for bit and address operations. An expression is a string or combination of an operator and one or more operands. The operator defines the action to be performed on the operand(s) such as computation of a value, instructions on an object or function, generation of side effects, or a combination of these. Examples of operators are given below. #define TRUE #define SIZE 1 200
#define FALSE 0
void lprintf(char*, int); void putchar(char c); char mark[SIZE+1]; void main(void){ int i,prime,k,count; count=0; for(i=0;i<=SIZE;i++) mark[i]=TRUE; for(i=0;i<=SIZE;i++){ if(mark[i]){ prime=i+i+3; lprintf("%d",prime); count++; if((count%8)==0) putchar('\n'); for(k=i+prime;k<=SIZE;k+=prime) mark[k]=FALSE; } } +=.................... Assignment operator ++ .......................................... == .......................................... Postfix operator Relational operator + ............................................ Arithmetic operator = ............................................................. ++ ........................................................... <= ........................................................... Assignment operator Postfix operator Relational operator + ............................................................. Arithmetic operator
User's Manual U14872EJ1V0UM
75
CHAPTER 5
OPERATORS AND EXPRESSIONS
lprintf("Total loop1: goto loop1; } lprintf(char *s,int;){ int j; char *ss; j=i; ss=s; } void puttchar(char c){ char d; d=c; }
%d\n", count);
76
User's Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
Table 5-1 shows the evaluation precedence of operators used in C. Table 5-1. Evaluation Precedence of Operators
Type of Expression Postfix Unary Cast Multiplicative Additive Bitwise shift Relational Equality Bitwise AND Bitwise XOR Bitwise OR Logical AND Logical OR Conditional Assignment Operator [ ] ( ) . - > ++ - - ++ - - & * + - ~ ! sizeof (type) */% +- << >> < > <= >= == != & ^ | && || ?: = *= /= %= += -= <<= >>= &= ^= | = , Linkage Priority Highest
Comma
Lowest
Operations in the same line contain the same priority. The arrow ( or ) in the Linkage column denotes that when an expression contains two or more operators of the same precedence, the operations are carried out in the direction of the arrow "" (from left to right) or "" (from right to left).
User's Manual U14872EJ1V0UM
77
CHAPTER 5
OPERATORS AND EXPRESSIONS
5.1
Primary Expressions
Primary expressions include the following. * Identifier declared as an object or function (identifier primary expression) * Constant (constant primary expression) * String literal (constant primary expression) * Expression enclosed in parentheses (parenthesized expression) An identifier which becomes a primary expression is a left-side value if an object is declared or a function locator if a function is declared. The data type of a constant is determined according to the value specified for the constant as explained in 2.4 Constants. String literal(s) become a left-side value that has a data type as explained in 2.5 String Literal.
5.2
Postfix Operators
A postfix operator is an operator that appears or is placed after an object or function. The primary expressions are explained on the following pages.
78
User's Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
(1) Subscript operator
Postfix Operators
[ ] Subscript Operator
FUNCTION The [ ] subscript operator specifies or refers to a single member of an array object. The array or expression "E1 [E2]" is evaluated as if it were "(*(E1+(E2)))". In other words, the value of E1 is a pointer to the first member of the array and E2 (if it is an integer) indicates the E2th member of E1 (counting from 0). With a multidimensional array, as many subscript operators as the number of dimensions must be connected. In the following example, x becomes an int type array of 3*5. In other words, x is an array which has three members each consisting of five int type members. int x[3][5];
A multidimensional array may be specified by connecting subscript operators. Assuming that E is an array of nth dimension (where n 2) consisting of i*j*...*k, the array can be specified with the n number of subscript operators. In this case, E becomes a pointer to an array of (n - 1)th dimension consisting of j*...*k. SYNTAX postfix-expression [subscripted expression]
NOTE A postfix expression must have a ".... pointer to object". The subscripted expression of an array must be specified with integral type data. The result of the expression will become "....." type.
User's Manual U14872EJ1V0UM
79
CHAPTER 5
OPERATORS AND EXPRESSIONS
(2) Function call
Postfix Operators
( ) Function Call
FUNCTION The postfix operator ( ) calls a function. The function to be called is specified with a postfix expression and argument(s) to passed to the function are indicated in parentheses ( ). The description related to the function includes the function prototype declaration, the function definition (the body of the function), and the function call. The function prototype declaration specifies the value a function returns, the type of argument, and the storage class. If the function prototype declaration is not referred to in a function call, each argument is extended with a general integer. This is called "default actual argument extension". Performing a function prototype declaration avoids default actual argument extension and detects the mistakes of the type and number of arguments and the type of the return value. Calling a function which has neither a storage class specification nor a data type specification such as "identifier ();" is interpreted as calling a function which has an external object and returns an int type which has no information on arguments. In other words, the following declaration will be made implicitly: extern int identifier ();
SYNTAX postfix-expression ( argument-expression list );
[Example of function call] int func(char,int); char a; int b,ret; void main(void){ ret=func(a,b); } int func(char c, int i){ . . . return i; } /* function definition */ /* function call */ /* function prototype declaration */
NOTE A function that returns an object other than array types can be called with this operator. The postfix expression must be of a pointer type to this function. In a function call including a prototype, the type of argument must be of a type that can be assigned to the corresponding parameter(s). The number of arguments must also be in agreement.
80
User's Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
(3) Structure and union member
Postfix Operators
. ->
<1> . (dot) operator FUNCTION The . (dot) operator (also called a member operator) specifies the individual members of a structure or union. The postfix expression is the name of the structure or union object to be specified, and the identifier is the name of the member. SYNTAX postfix-expression . identifier
<2> -> (arrow) operator FUNCTION The -> (arrow) operator (also called an indirect membership operator) specifies the individual members of a structure or union. The postfix expression is the name of the pointer to the structure or union object to be specified, and the identifier is the name of the member. SYNTAX postfix-expression -> identifier
User's Manual U14872EJ1V0UM
81
CHAPTER 5
OPERATORS AND EXPRESSIONS
Postfix Operators
. ->
[Examples of `.', `->' operators] #include union{ struct{ int type; }n; struct{ int type; int intnode; }ni; struct { int type; struct{ long longnode; }*nl_p; }nl; }u; void func(void){ u.nl.type=1; u.nl.nl_p->longnode=-31415L; /*...*/ if(u.n.type==1) u.nl.nl_p->longnode=labs(u.nl.nl_p->longnode); }
82
User's Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
(4) Postfix increment/decrement operators
Postfix Operators
++ - -
<1> Postfix increment operator FUNCTION The postfix increment operator increments the value of an object by 1. This increment operation is performed by taking the data type of the object into account. SYNTAX postfix-expression ++
<2> Postfix decrement operator FUNCTION The postfix decrement operator decrements the value of an object by 1. This decrement operation is performed by taking the data type of the object into account. SYNTAX postfix expression --
NOTE The operand of the postfix increment or decrement operator must be a modifiable Lvalue unqualified). (qualified or
User's Manual U14872EJ1V0UM
83
CHAPTER 5
OPERATORS AND EXPRESSIONS
5.3
Unary Operators
A unary operator performs an operation on one object or parameter (i.e., operand). The following unary operators are available. * Prefix increment and decrement operators ++ -- * Address and indirect operators &* * Unary arithmetic operators + - ~ ! * sizeof operator sizeof
The unary operators are explained in the following pages.
84
User's Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
(1) Prefix increment/decrement operators
Unary Operators
++ - -
<1> Prefix increment operator FUNCTION The prefix increment operator increments the value of an object by 1. The expression "++E" of the prefix increment operator will produce the same result as the following expression. E=E+1 or E += 1
SYNTAX ++ unary-expression
<2> Prefix decrement operator FUNCTION The prefix decrement operator decrements the value of an object by 1. The expression "- -E" of the prefix decrement operator will produce the same result as the following expression: E=E-1 or E -= 1
SYNTAX -- unary-expression
User's Manual U14872EJ1V0UM
85
CHAPTER 5
OPERATORS AND EXPRESSIONS
(2) Address and indirect operators
Unary Operators
&*
<1> Unary & operator FUNCTION The unary & operator returns the pointer of a specified object (i.e., the address of the variable it precedes). SYNTAX & operand
<2> Unary * operator FUNCTION The unary * operator returns the value indicated by a specified pointer (i.e., takes the value of the variable it precedes and uses that value as the address of the information in memory). SYNTAX * operand
NOTE The operand of the unary & operator must be a left-side value referring to an object not declared with the register storage class specifier. Neither a function locator nor a bit field can be used as the operand of this unary operator. The operand of the unary * operator must have a pointer type.
86
User's Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
(3) Unary arithmetic operators (+ - ~ !)
Unary Operators
+-~!
FUNCTIONS The + (unary plus) operator performs positive integral promotion on its operand. The - (unary minus) operator performs negative integral promotion on its operand. The ~ (tilde) operator is a bitwise one's complement operator which inverts all the bits in a byte of its operand. The ! NOT or logical negation operator returns 0 if its operand is 0 and 1 if it is not 0. In other words, the operator changes each 0 to 1 and 1 to 0. SYNTAX + operand - operand ~ operand ! operand
User's Manual U14872EJ1V0UM
87
CHAPTER 5
OPERATORS AND EXPRESSIONS
(4) sizeof operator
Unary Operators
sizeof Operator
FUNCTION The sizeof operator returns the size of a specified object in bytes. The return value is governed by the data type of the object and the value of the object itself is not evaluated. The value to be returned by an unsigned char or signed char object (including its qualified type) on which a sizeof operation is performed is 1. With an array type object, the return value will be the total number of bytes in the array. With a structure or union type object, the result value will be the total number of bytes that the object would occupy including bytes necessary to pad out to the next appropriate alignment boundary. The type of the sizeof operation result is an integral type and its name is size_t. This name is defined in the header. The sizeof operator is used mainly to allocate memory areas and transfer data to/from the I/O system. SYNTAX sizeof unary-expression or sizeof (type-name)
EXAMPLE The following example finds the number of elements of an array by dividing the total number of bytes in the array by the size of a single element. Num becomes 5. int num; char array[]= {0, 1, 2, 3, 4}; void func(void){ num = sizeof array / sizeof array [0]; }
NOTE An expression that has a function type or incomplete type and a left-side value which refers to a bit field object cannot be used as the operand of this operator.
88
User's Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
5.4
Cast Operator
A cast is a special operator which forces one data type to be converted into another. The cast operator is mainly used when converting a pointer type.
Cast Operator
(type-name)
FUNCTION The cast operator converts the data type of another object (or the result of another expression) into the type specified in parentheses ( ). SYNTAX (type-name) expression
EXAMPLE void func(void){ int val; float f; f=3.14F; val=(int)f; val=*(int *)0x10000; } /* val becomes 3 by cast */ /* cast constant */
User's Manual U14872EJ1V0UM
89
CHAPTER 5
OPERATORS AND EXPRESSIONS
5.5
Arithmetic Operators
Arithmetic operators are divided into multiplicative operators and additive operators, in that order of priority. Multiplicative operators find the product, quotient, and remainder of two operands. Additive operators find the sum and difference of two operands. * Multiplicative operators * * Additive operators + / - %
Table 5-2. Signs of Division/Remainder Operation Result
b a/b + + a - - + + - - a - - - + a%b + + - + b
Remark
a and b indicate the operands.
Division is performed with two integers whose sign, if any, is removed through the usual arithmetic conversion and the result will be truncated towards 0 if necessary. Likewise, a remainder or modulo division operation is performed with two integers whose sign, if any, is removed through the usual arithmetic conversion. Table 5-2 shows the results of calculations only on the signs of two operands in division and remainder operations, respectively. The following explain multiplying operators and adding operators. E1 and E2 used in the explanation of syntax indicate operands or expressions.
90
User's Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
(1) Multiplicative operators
Multiplicative Operators
*/%
<1> * operator FUNCTION The * operator performs normal multiplication on two operands and returns the product. SYNTAX E1 * E2
<2> / operator FUNCTION The / operator performs normal division on two operands and returns the quotient. SYNTAX E1 / E2
<3> % operator FUNCTION The % operator performs a remainder (or modulo division) operation on two operands and returns the remainder in the result. SYNTAX E1 % E2
User's Manual U14872EJ1V0UM
91
CHAPTER 5
OPERATORS AND EXPRESSIONS
(2) Additive operators
Additive Operators
+-
<1> + operator FUNCTION The + operator performs addition on two operands and returns the sum of the two numbers. SYNTAX E1 + E2
<2> - operator FUNCTION The - operator performs subtraction on two operands and returns the difference between the two numbers (the first operand minus the second operand). SYNTAX E1 - E2
92
User's Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
5.6
Bitwise Shift Operators
A shift operator shifts its first (left) operand in the direction (left or right) indicated by the operator by the number of bits specified by its second operand. There are the following two shift operators. * shift operator << >>
Table 5-3. Shift Operations
a<>b + bNote 0
Note The table indicates when the right operand is greater than the number of bits in the left operand or when an overflow occurs in the result of the shift operation. If the right operand is negative, the value is processed as an unsigned positive number. Remark a and b indicate the operands.
The shift operators are explained in the following pages. E1 and E2 indicate operands or expressions.
User's Manual U14872EJ1V0UM
93
CHAPTER 5
OPERATORS AND EXPRESSIONS
Shift Operators
<< >>
<1> Left shift (<<) operator FUNCTION The << operator shifts the left operand to the left the number of bits specified by the right operand and fills zeros in vacated bits. If the left operand E1 has an unsigned type in "E1 << E2", the result will become a value obtained by multiplying E1 by the E2th power of 2. SYNTAX E1 << E2
<2> Right shift (>>) operator FUNCTION The >> operator shifts the left operand to the right the number of bits specified by the right operand. If the left operand is unsigned, zeros are filled in vacated bits (logical shift). If the left operand is signed, a copy of the sign bit is filled in vacated bits. If the left operand E1 is unsigned or signed and has a non-negative value in "E1>>E2", the result will become a value obtained by dividing E1 by the E2th power of 2. SYNTAX E1 >> E2
94
User's Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
5.7
Relational Operators
There are two types of operators to indicate the relationship between two operands: "relational operators" and "equality operators". The relational operators indicate the value relationship between two operands such as greater than and less than. The equality operators indicate that two operands are equal or not equal. The relational operators and equality operators are shown below. * Relational operators * Equality operators < == > != <= >=
The value relationship between two pointers compared by relational operators is determined by the relative location in the address space of the object indicated by the pointer. In this compiler, relational operators and equality operators generate `1' if the specified relationship is true and `0' if it is false. The results have int type. The relational operators and equality operators are explained in the following pages. E1 and E2 used in the explanation of syntax indicate operands or expressions.
User's Manual U14872EJ1V0UM
95
CHAPTER 5
OPERATORS AND EXPRESSIONS
(1) Relational operators
Relational Operators
< > <= >=
<1> < (less than) operator FUNCTION The < operator returns 1 if the left operand is less than the right operand; otherwise 0 is returned. SYNTAX E1 < E2
<2> > (greater than) operator FUNCTION The > operator returns 1 if the left operand is greater than the right operand; otherwise 0 is returned. SYNTAX E1 > E2
<3> <= (less than or equal) operator FUNCTION The <= operator returns 1 if the left operand is less than or equal to the right operand; otherwise 0 is returned. SYNTAX E1 <= E2
96
User's Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
Relational Operator
< > <= >=
<4> >= (greater than or equal) operator FUNCTION The >= operator returns 1 if the left operand is greater than or equal to the right operand; otherwise 0 is returned. SYNTAX E1 >= E2
User's Manual U14872EJ1V0UM
97
CHAPTER 5
OPERATORS AND EXPRESSIONS
(2) Equality operators
Equality Operators
= = !=
<1> = = (equal) operator FUNCTION The = = operator returns 1 if its two operands are equal to each other; otherwise 0 is returned. SYNTAX E1 == E2
<2> != (not equal) operator FUNCTION The != operator returns 1 if both operands are not equal to each other; otherwise 0 is returned. SYNTAX E1 != E2
98
User's Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
5.8
Bitwise Logical Operators
Bitwise logical operators perform a specified logical operation on the value of an object in bit units. The bitwise logical expressions include bitwise AND (&), bitwise exclusive OR ( ^ ), and bitwise inclusive OR ( | ). Each logical operation is indicated by the operators shown below. * Betwise AND operator * Bitwise XOR operator * Bitwise OR operator & ^ |
The bitwise logical operators are explained in the following pages. E1 and E2 used in the explanation of syntax indicate operands or expressions.
User's Manual U14872EJ1V0UM
99
CHAPTER 5
OPERATORS AND EXPRESSIONS
(1) Bitwise AND operator
Bitwise AND Operator
&
FUNCTION The & operator is a bitwise AND operator which returns an integral value that has "1" bits in positions where both operands have "1" bits and that has "0" bits everywhere else. The bitwise AND operator must be specified with an "& operator". Table 5-4. Bitwise AND Operator
Value of Each Bit in Left Operand 1 Value of each bit in right operand 1 0 1 0 0 0 0
SYNTAX E1 & E2
100
User's Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
(2) Bitwise XOR operator
Bitwise XOR Operator
^
FUNCTION The ^ (caret) operator is a bitwise exclusive OR operator which returns an integral value that has a "1" bit in each position where exactly one of the operands has a "1" bit and that has a "0" bit in each position where both operands have a "1" bit or both have a "0" bit. Table 5-5. Bitwise XOR Operator
Value of Each Bit in Left Operand 1 Value of each bit in right operand 1 0 0 1 0 1 0
SYNTAX E1 ^ E2
User's Manual U14872EJ1V0UM
101
CHAPTER 5
OPERATORS AND EXPRESSIONS
(3) Bitwise inclusive OR operator
Bitwise Inclusive OR Operator
|
FUNCTION The | operator is a bitwise inclusive OR operator which returns an integral value that has a "1" bit in each position where at least one of the operands has a "1" bit and that has a "0" bit in each position where both operands have a "0" bit. Table 5-6. Bitwise OR Operator
Value of Each Bit in Left Operand 1 Value of each bit in right operand 1 0 1 1 0 1 0
SYNTAX E1 | E2
102
User's Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
5.9
Logical Operators
Logical operators perform logical OR and logical AND operations. A logical OR operation is specified with a logical OR operator, and a logical AND operation is specified with a logical AND operator. Each operator is shown below. * Logical AND operator * Logical OR operator && ||
Each operand of both the operators returns the value of int type `0' or `1'. The following explains each logical operator. E1 and E2 used in the explanation of syntax indicate operands or expressions.
User's Manual U14872EJ1V0UM
103
CHAPTER 5
OPERATORS AND EXPRESSIONS
(1) Logical AND operator
Logical AND Operator
&&
FUNCTION The && operator performs a logical AND operation on two operands and returns a "1" if both operands have nonzero values; otherwise a "0" is returned. The type of the result is int. Table 5-7. Logical AND Operator
Value of Left Operand Zero Value of right operand Zero Nonzero 0 0 Nonzero 0 1
SYNTAX E1 && E2
NOTE This operator always evaluates its operands from left to right. If the value of the left operand is "0", the right operand is not evaluated.
104
User's Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
(2) Logical OR operator
Logical OR Operator
||
FUNCTION The | | operator performs a logical OR operation on two operands and returns a "0" if both operands are zero; otherwise a "1" is returned. The type of the result is int. Table 5-8. Logical OR Operator
Value of Each Bit in Left Operand Zero Value of each bit in right operand Zero Nonzero 0 1 Nonzero 1 1
SYNTAX E1 || E2
NOTE This operator always evaluates its operands from left to right. If the value of the left operand is nonzero, the right operand is not evaluated.
User's Manual U14872EJ1V0UM
105
CHAPTER 5
OPERATORS AND EXPRESSIONS
5.10 Conditional Operators
Conditional operators judge the processing to be performed next by the value of the first operand. Conditional operators judge by `?' and `:'. The conditional operators are explained below.
Conditional Operators
?:
FUNCTION If the value of the first operand is nonzero, it evaluates the second operand before the colon. If the value of the first operand is zero, it evaluates the third operand after the colon. The result of the entire conditional expression will be the value of the second or third operand. SYNTAX 1st-operand ? 2nd-operand : 3rd-operand
EXAMPLE #define TRUE char flag; int ret; int func(){ ret=flag ? TRUE : FALSE; return ret; } 1
#define FALSE 0
NOTE If both the second and third operand types are arithmetic types, normal arithmetic type conversion is performed to make them common types. The type of result is the common type. If both the operand types are structure types or union types, the result becomes those types. If both the operand types are void types, the result is void type.
106
User's Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
5.11 Assignment Operators
Assignment operators include a simple assignment expression that stores the right operand in the left operand and a compound assignment expression that stores the result of an operation on both operands in the left operand. The assignment operators are shown below. * Assignment Operators = *= /= &= ^= |=
%=
+=
-=
<<=
>>=
The assignment operators are explained in the following pages. E1 and E2 used in the explanation of syntax indicate operands or expressions.
User's Manual U14872EJ1V0UM
107
CHAPTER 5
OPERATORS AND EXPRESSIONS
(1) Simple assignment operator
Simple Assignment Operator
=
FUNCTION The = operator converts the right operand (expression) to the type of the left operand before the value is stored in the left object. In the following example, the value of an int type to be returned from the function by the type conversion of the simple assignment expression will be converted to a char type and an overflow in the result will be truncated. The comparison of the value with "-1" will then be made after the value is converted back to the int type. If the variable "c" declared without a qualifier is not interpreted as unsigned char, the result of the variable will not become negative and its comparison with "-1" will never result in equal. In such a case, the variable "c" must be declared with an int type to ensure complete portability. int f(void); char c; /*...*/ ((c=f())==-1) /*...*/
SYNTAX E1 = E2
108
User's Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
(2) Compound assignment operators
Compound Assignment Operators
*= /= %= += -= <<= >>= &= ^= |=
FUNCTION The compound assignment operators perform a specified operation on both operands and store the result in the left object. The value to be stored in the left object will be converted to the type of the left operand. The compound assignment expression "E1 op = E2" (where op indicates a suitable binary operator) is equivalent to the simple assignment expression "E1 = E1 op (E2)", except that the left operand (E1) is only evaluated once. The following compound assignment expressions will produce the same result as the respective simple assignment expressions on the right. a*=b; a/=b; a%=b; a+=b; a-=b; a<<=b; a>>=b; a&=b; a^=b; a|=b; a=a*b; a=a/b; a=a%b; a=a+b; a=a-b; a=a<>b; a=a&b; a=a^b; a=a|b;
SYNTAX E1 *= E2 E1 /= E2 E1 %= E2 E1 += E2 E1 -= E2 E1 <<= E2 E1 >>= E2 E1 &= E2 E1 ^= E2 E1 |= E2
User's Manual U14872EJ1V0UM
109
CHAPTER 5
OPERATORS AND EXPRESSIONS
5.12 Comma Operator
Comma Operator
,
FUNCTION The comma operator evaluates the left operand as a void type (that is, ignores its value) and then evaluates the right operand. The type and value of the result of the comma expression are the type and value of the right operand. If a comma has another meaning (as in a list of function arguments or in a list of variable initializations), comma expressions must be enclosed in parentheses. In other words, the comma operator described in this chapter will not appear in such a list. In the following example, the comma operator finds the value of the second argument of the function "f ()". The value of the second argument becomes 5. Int a, c, t; void main(void) { f(a,(t=3,t+2),c); }
SYNTAX E1 , E2
110
User's Manual U14872EJ1V0UM
CHAPTER 5
OPERATORS AND EXPRESSIONS
5.13 Constant Expressions
Constant expressions include general integral constant expressions, arithmetic constant expressions, address constant expressions, and initialization constant expressions. Most of these constant expressions can be calculated at translation time instead of execution time. In a constant expression, the following operators cannot be used except when they appear inside sizeof expressions. * Assignment operators * Increment operators * Decrement operators * Function call operator * Comma operator (1) General integral constant expression A general integral constant expression has a general integral type. The following operands may be used. * Integer constants * Enumerated value constants * Character constants * sizeof expressions * Floating point constants (2) Arithmetic constant expression An arithmetic constant expression has an integral type. The following operands may be used. * Integer constants * Enumerated value constants * Character constants * sizeof expressions * Floating point constants (3) Address constant expression An address constant expression is a pointer to an object that has a static storage duration or a pointer to a function locator. Such an expression must be created explicitly using the unary & operator or implicitly using an expression with an array type or function type. The following operands may be used. * Array subscript operator [ ] * . (dot) operator * -> (arrow) operator * & address operator * * indirection operator * Pointer casts However, none of these operators can be used to access the value of an object.
User's Manual U14872EJ1V0UM
111
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
This chapter describes the program control structures of C language and the statements to be executed in C. Generally speaking, no matter how complicated a process is, it can be expressed with three basic control structures. These three control structures are: sequential, selection, and iteration. An additional control structure, branch, is used to change the flow of a program by force. (1) Sequential processing Statements in a program are executed one by one from top to bottom in the order of their description in the program. (2) Conditional control (selection) processing According to the status of the program under execution, the next executable statement is selected and executed. The selection condition is specified in a control statement. The control statement determines which of the two alternative statement groups or multiway (three or more) alternative statement groups is to be executed. (3) Looping (iteration) processing The same processing is executed two or more times. The execution of an executable statement is repeated a specified number of times while in the state indicated by the control statement. (4) Branch processing The current program flow is forcibly interrupted and control is transferred to a specified label. Program execution starts from the statement next to the specified label. There are six types of statements used in C. * Labeled statement............................... ............................................................ * Compound statement (block) .............. * Expression statement.......................... * Selection statement............................. ............................................................ * Iteration statement .............................. ............................................................ * Branch statement ................................ Causes a branch according to the value of the switch statement and the destination of the goto statement Collects two or more statements to be processed as one unit A statement consisting of an expression and a semicolon Selects a statement out of several statements according to the value of the expression Repeatedly performs a statement called the body of a loop until the control expression becomes equal to 0. Causes an unconditional branch to different destination
112
User's Manual U14872EJ1V0UM
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
A description example of these statements is shown below. [Description example] #define SIZE #define TRUE 10 1
#define FALSE 0 extern void putchar(char); extern void lprintf(char *, int); char mark [SIZE+1]; int i, prime, k, count;
void main(void){
count = 0; for(i = 0 ; i <= SIZE ; i++) mark [i] = TRUE ; for(i = 0 ; i <= SIZE ; i++) { if(mark[i]){ prime = i + i + 3; lprintf("%d", prime); if((count%8) == 0) putchar('\n'); for(k = i + prime ; k <= SIZE ; k += prime) mark [k] = FALSE; } } lprintf("Total %d\n", count); loop1; goto loop1; } / * loop1: ................................ / * goto ................................... Labeled statement * / Branch statement * / / * if ............................. Conditional statement * / / * for........................... / * if ............................. Iteration statement */ Conditional statement */ /* for............................ Iteration statement */
User's Manual U14872EJ1V0UM
113
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
6.1
Labeled Statements
A labeled statement specifies the destination of a switch or goto statement. The switch statement selects the statement specified by a control expression from among statements with two or more options. The labeled statement becomes the label of the statement to be executed by the switch statement. unconditional branching to the applicable label from the normal flow of processing. The syntax of labeled statements is given below. The goto statement causes
114
User's Manual U14872EJ1V0UM
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
(1) case label
Labeled Statements
case label
FUNCTION case labels are used only in the body of a switch statement to enumerate values to be taken by the control expression of the switch statement. SYNTAX case constant-expression : statement
EXAMPLE 1 int f(void),i; void main(void){ /* ... */ switch(f()){ case 1: i=i+4; break; case 2: i=i+3; break; case 3: i=i+2; } /* ... */ }
EXPLANATION In example 1, if the return value of f( ) is 1, the first case clause (statement) is selected and the expression "i=i+4" is executed. Likewise, if the return value of f( ) is 2 or 3, the second or third case statement is selected, respectively. Each break statement in the above example is for exiting the switch statement. As in this example, case labels are used when two or more options are involved.
User's Manual U14872EJ1V0UM
115
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
Labeled Statements
case label
EXAMPLE 2 int i; /* ... */ i = 2; switch(i) { case 1: i=i+4; case 2: i=i+3; case 3: i=i+2; } /* ... */ }
void main (void){
EXPLANATION In example 2, the processing starts in the second case statement since i is 2. The third statement is also consecutively performed since the case statement does not include a break statement. Thus, if the constant expression and the control expression in the case statement match, the programs thereafter are performed sequentially. A break statement is used to exit the switch statement.
116
User's Manual U14872EJ1V0UM
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
(2) default label
Labeled Statements
default label
FUNCTION A default label is a special case label used only in the body of a switch statement to specify a process to be executed by C if the value of the control expression does not match any of the case constants. SYNTAX default: statement EXAMPLE int f (void), i ;
switch (f()) { case 1: i=i+4; break; case 2: i=i+3; break; case 3: i=i+2; default: i = 1; }
EXPLANATION In the above example, if the return value of f( ) is 1, 2, or 3, the corresponding case clause (statement) is selected and the expression that follows the case label is executed. Each break statement in the above example is for exiting the switch statement. If the return value of f( ) is other than 1 to 3, the expression that follows the default label is executed. In this case, the value of i becomes 1.
User's Manual U14872EJ1V0UM
117
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
6.2
Compound Statements (Blocks)
A compound statements consist of two or more statements grouped together with enclosing braces and executed as one unit syntax-wise. In other words, by enclosing zero or more declarations followed by zero or more statements all in braces, these statements can be processed as a compound statement whenever a single statement is expected.
6.3
Expression Statements and Null Statements
An expression statement consists of a statement and a semicolon. A null statement consists of only a semicolon and is used for labels that require a statement and in looping that does not need any body. The description examples of expression statements and null statements are given below. As in the following example, for a function to be called as an expression statement merely to obtain side effects, the value of its return value can be discarded by using a cast expression. int p(int) ; void main(void){ /* ... */ (void)p(0) ; }
A null statement can be used as the body of a looping statement as shown below. char *s ; void main(void){ /*...*/ while (*s++ != '0') ; /*...*/ }
In addition, it can be used to place a label before a brace ( } ) which closes a compound statement as shown below. void func(void){ /*...*/ while(loop1){ /*...*/ while(loop2){ /*...*/ if(want_out) goto end_loop1; /*...*/ } end_loop1:; } }
118
User's Manual U14872EJ1V0UM
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
6.4
Selection Statements
Selection statements include if and switch statements. The if or switch statement allows the program to choose one of several groups of statements to execute, based on the value of the control expression enclosed in parentheses. The control flows of the if and switch statements are illustrated in Figure 6-1 below. Figure 6-1. Control Flows of Selection Statements
Control flow of if statement
if condition True
False
Executes statement that follows if.
Executes statement that follows else.
Control flow of switch statement
switch
case 1
case 2
case 3
...
default :
User's Manual U14872EJ1V0UM
119
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
(1) if and if ... else statements
Selection Statements
if, if ... else
FUNCTION An if statement executes the statement that follows the control expression enclosed in parentheses if the value of the control expression is nonzero. An if ... else statement executes the statement-1 that follows the control expression if the value of the control expression is nonzero or the statement-2 that follows else if the value of the control expression is zero. SYNTAX if (expression) statement if (expression) statement-1 else statement-2
EXAMPLE unsigned char uc;
void func (void){ if( uc < 10 ){ /* 111 */ } else{ /* 222 */ } }
EXPLANATION In the above example, if the value of uc is less than 10 based on the control expression in the if statement, the block "{/*111*/}" is executed. If the value is greater than 10, the block "{/*222*/}" is executed. NOTE When the processing after if statement/if...else statement is not enclosed with "{ }", only the processing of one line after the if statement/if...else statement is performed regarding it as the body.
120
User's Manual U14872EJ1V0UM
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
(2) switch statement
Selection Statements
switch
FUNCTION A switch statement has a multiway branching structure and passes control to one of a series of statements that have the case labels in the switch body depending on the value of the control expression enclosed in parentheses. If no case label that corresponds to the control expression exists, the statement that follows the default label is executed. If no default label exists, no statement is executed. SYNTAX switch (expression) statement
EXAMPLE extern void func(void); unsigned char mode; void main(void){ switch(mode){ case 2: mode=8; break; case 4: mode=2; break; case 8: func(); } }
NOTE The same value cannot be set in each case label in the switch statement. Only one default label can be used in the switch statement.
User's Manual U14872EJ1V0UM
121
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
6.5
Iteration Statements
An iteration statement executes a group of statements in the loop body as long as the value of the control expression enclosed in parentheses is true (nonzero). C has the following three types of iteration statements. * while statement * do statement * for statement
The control flow of each type of iteration statement is illustrated in Figure 6-2 below. Figure 6-2. Control Flows of Iteration Statements
Control flow of while loop Loop Loop while condition True Executes statement (s) that follow while. False Executes statement (s) that follow do. Initialize Control flow of do-while loop Loop Control flow of for loop
for condition True
False
True
while condition False
Executes statement (s) that follow for.
Reevaluates control expression.
122
User's Manual U14872EJ1V0UM
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
(1) while statement
Iteration Statements
while statement
FUNCTION A while statement executes one or more statements (the body of the while loop) several times as long as the value of the control expression enclosed in parentheses is true (nonzero). The while statement evaluates the control expression before executing its loop body. SYNTAX while (expression) statements
EXAMPLE int i, x ; i=1, x=0 ;
void main (void){
while( i < 11 ){ x += i ; i++ ; } }
EXPLANATION The above example finds the sum total of integers from 1 to 10 for x. The two statements enclosed in braces are the body of this while loop. The control expression "i<11" returns 0 if the value of i becomes 11. For this reason, the loop body is executed repeatedly as long as the value of i is less than 11 (between 1 and 10). "while(1) {statement}" is used to endlessly perform a loop statement.
User's Manual U14872EJ1V0UM
123
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
(2) do statement
Iteration Statements
do statement
FUNCTION A do statement executes the body of the loop and then tests the control expression enclosed in parentheses to see if its value is true (nonzero). The do statement evaluates the control expression after the loop body has been executed. SYNTAX do statements while (expression);
EXAMPLE int i, x; void main(void){ i=1,x=0; do{ x+=i; i++; }while(i<11); }
EXPLANATION The above example finds the sum total of integers from 1 to 10 for x. The two statements enclosed in braces are the body of this do ... while loop. The control expression "i<11" returns 0 if the value of i becomes 11. For this reason, the loop body is executed repeatedly as long as the value of i is less than 11 (between 1 and 10). The body of the loop is always performed once or more since the control expression of a do statement is evaluated after execution.
124
User's Manual U14872EJ1V0UM
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
(3) for statement
Iteration Statements
for statement
FUNCTION A for statement executes the body of the for loop a specified number of times as long as the value of the control expression is nonzero (true). Of the three expressions inside the parentheses separated by semicolons, the first expression is an initializing statement to initialize a variable to be used as a counter and is executed only once in the beginning of the loop, the second is the control expression for testing the counter value, and the third is a step statement executed at the end of every loop, after which the variable is reevaluated. SYNTAX for(1st-expression ; 2nd-expression ; 3rd-expression) statements
EXAMPLE int i,x=0; for(i=1;i<11;++i) x+=i;
EXPLANATION The above example finds the sum total of integers from 1 to 10 for x. "x+=i" is the body of this for loop. The control expression "i<11" returns 0 if the value of i becomes 11. For this reason, the loop body is executed repeatedly as long as the value of i is less than 11 (between 1 and 10). NOTE When the processing after the for statement is not enclosed with "{ }", only the processing of one line after the for statements is regarded as the body of the loop of the for statement. The first and the third expression of a for statement can be omitted. When the second expression is omitted, it is replaced with a constant other than 0. The description of "for (; ;) statement" is used to endlessly perform the body of the loop.
User's Manual U14872EJ1V0UM
125
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
6.6
Branch Statements
A branch statement is used to exit from the current control flow and transfer control to elsewhere in the program. Branch statements include the following four statements. * goto statement * continue statement * break statement * return statement
The control flow of each type of branch statement is shown in Figure 6-3. Figure 6-3. Control Flows of Branch Statements
continue break
Loop
Loop
continue
break
126
User's Manual U14872EJ1V0UM
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
(1) goto statement
Branch Statements
goto
FUNCTION A goto statement causes program execution to unconditionally jump to the label name specified in the goto statement within the current function. SYNTAX goto identifier ;
EXAMPLE do{ /*...*/ goto point ; /*...*/ }while(/*...*/) ; /*...*/ point: ;
EXPLANATION In the above example, when control is passed to the goto statement, C unconditionally jumps out of the current do ... while loop processing and transfers control to the statement next to "point". NOTE The label name (branch destination) to be specified in a goto statement must have been specified within the current function that includes the goto statement. In other words, a goto can branch only within the current function - not from one function to another.
User's Manual U14872EJ1V0UM
127
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
(2) continue statement
Branch Statements
continue
FUNCTION A continue statement is used in the loop body of an iteration statement. continue ends one cycle of the loop by transferring control to the end of the loop body. When a continue statement is enclosed by more than one loop, it ends a cycle of the smallest enclosing loop. SYNTAX continue ;
EXAMPLE while(/*...*/){ /*...*/ continue; /*...*/ contin:; }
EXPLANATION In the above example, when the while loop processing by C reaches the continue statement, C unconditionally branches to the label "contin". The label "contin" indicates the branch destination and may be omitted. The same branching operation may be performed by using "goto contin ;" instead of continue. NOTE A continue statement can only be used in the body of loops.
128
User's Manual U14872EJ1V0UM
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
(3) break statement
Branch Statements
break
FUNCTION A break statement may appear in the body of an iteration or switch statement and causes control to be transferred to the statement next to the iteration or switch statement. SYNTAX break ;
EXAMPLE int i;
unsigned char count, flag; void main(void){ /*...*/ for(i = 0;i < 20;i++){ switch(count){ case 10: flag = 1; break; default: func() ; } if (flag) break; } } /*exit for loop */ /* exit switch statement */
EXPLANATION In the above example, break statements are used so that more than required evaluations are not performed in the body of the switch statement. If the corresponding case label is found in evaluating the switch statement, the break statement causes C to exit from the switch statement. NOTE A break statement can only be used in the loop or switch body.
User's Manual U14872EJ1V0UM
129
CHAPTER 6
CONTROL STRUCTURES OF C LANGUAGE
(4) return statement
Branch Statements
return
FUNCTION A return statement exits the function that includes the return and passes controls to the function that called the return, and calls and returns the value of the return statement expression as the value of the function call expression. Two or more return statements may be used in a function. Using the closing brace " } " at the end of a function produces the same result as when a return statement without an expression is executed. SYNTAX return expression ;
EXAMPLE int f(int); void main(void){ /*...*/ int i=0,y=0; y=f(i); /*...*/ } int f(int i){ int x=0; /*...*/ return(x); }
EXPLANATION In the above example, when control is passed to the return statement, the function f() returns a value to the function main. Because the value of the variable "x" is returned as the return value, the assignment operator causes the variable "y" to be substituted with the value of the variable "x". NOTE With a void type function, an expression that indicates a return value cannot be used for a return statement.
130
User's Manual U14872EJ1V0UM
CHAPTER 7
STRUCTURES AND UNIONS
A structure or union is a collection of member objects that have different types and grouped under one given name. The member objects of a structure are allocated successively to memory space, while the member objects of a union share the same memory.
User's Manual U14872EJ1V0UM
131
CHAPTER 7
STRUCTURES AND UNIONS
7.1
Structures
As mentioned earlier, a structure is a collection of member objects successively allocated to memory space. (1) Declaration of structure and structure variable A structure declaration list and a structure variable are declared with the keyword struct. Any tag name can be given to the structure declaration list. Subsequently, the structure variables of the same structure may be declared using this tag name. [Declaration of structure] struct tag name {structure declaration list} variable name;
In the following example, in the first struct declaration, the int type array "code" and char type arrays name, addr, and tel, with the tag name "data" are specified and no1 is declared as the structure variable. In the second struct declaration, the structure variables no2, no3, no4, and no5, which have the same structure as no1 are declared. [Example] struct data{ int code; char name[12]; char addr[50]; char tel[12]; }no1; struct data no2,no3,no4,no5;
(2) Structure declaration list The structure declaration list specifies the structure of a structure type to be declared. Individual elements in the structure declaration list are called members and an area is allocated for each of these members in the order of their declaration. In the following [Example of structure declaration list], an area is allocated in the order of variable a, array b, and two-dimensional array c. Neither an incomplete type (an array of unknown size) nor a function type can be specified as the type of each member. Therefore, the structure itself cannot be included in the structure declaration list. Each member can have any object type other than the above two types. A bit field that specifies each member in bits can also be specified. If a variable takes a binary value "0" or "1", the minimum required number of bits is specified as 1 for a bit field. By this specification of the minimum required number of bits with the bit field, two or more members can be stored in an integer area. [Example of structure declaration list] int a; char b[7]; char c[5][10];
132
User's Manual U14872EJ1V0UM
CHAPTER 7
STRUCTURES AND UNIONS
[Example of bit field declaration] struct bf_tag{ unsigned int a:2; unsigned int b:3; unsigned int c:1; }bit_field; (3) Arrays and pointers Structure variables may also be declared as an array or referenced using a pointer. [Structure arrays] An array of structures is declared in the same ways as other objects. struct data{ char name[12]; char addr[50]; char tel[12]; }; struct data no[5]; [Structure pointers] A pointer to a structure has the characteristics of the structure indicated by the pointer. In other words, if a structure pointer is incremented, adding the size of the structure to the pointer points to the next structure. In the following example, "dt_p" is a pointer to the value of "struct data" type. Here, if the pointer "dt_p" is incremented, the pointer becomes the same value as "&no[1]". struct data no[5]; struct data *dt_p=no; bit field
(4) How to refer to structure members A structure member (or structure element) may be referenced in two ways: one by using a structure variable and the other by using a pointer to a variable. [Reference by using a structure variable] The . (dot) operator is used for referring to a structure member by using a structure variable. struct data{ char name[12]; char addr[50]; char tel[12]; }no[5]={"NAME","ADDR","TEL"};*data_ptr=no; void main(){ char c ; c=no[0].name[1]; }
User's Manual U14872EJ1V0UM
133
CHAPTER 7
STRUCTURES AND UNIONS
[Reference by using a pointer to a variable] The -> (arrow) operator is used for referring to a structure member by using a pointer to a variable. struct data{ char name[12]; char addr[50]; char tel[12]; }no[5]={"NAME","ADDR","TEL"},*data_ptr=no; void main(){ char c; data_ptr->tel[3]='E'; }
7.2
Unions
As mentioned earlier, a union is a collection of members that share the same memory space (or overlap in memory). (1) Declaration of union and union variable A union declaration list and a union variable are declared with the keyword union. Any name called a tag name can be given to the union declaration list. Subsequently, the union variables of the same union may be declared using this tag name. [Declaration of union] union tag name {union declaration list} variable name;
In the following example, in the first union declaration, char type arrays "name", "addr", and "tel" with the tag name "data" are specified and "no1" is declared as the union variable. In the second union declaration, the union variables "no2, no3, no4, and no5" which are of the same union as "no1" are declared. union data{ char name[12]; char addr[50]; char tel[12]; }no1; union data no2,no3,no4,no5;
(2) Union declaration list A union declaration list specifies the structure of a union type to be declared. Individual elements in the union declaration list are called members and an area is allocated for each of these members in the order of their declaration. In the following [Example of union declaration list], an area is allocated to `c', which becomes the largest area of the members. The other members are not allocated new areas but use the same area. Neither an incomplete type (an array of unknown size) nor a function type can be specified as the type of each member same as the union declaration list. Each member can have any object type other than the above two types.
134
User's Manual U14872EJ1V0UM
CHAPTER 7
STRUCTURES AND UNIONS
[Union declaration list] int a; char b[7]; char c[5][10];
(3) Union arrays and pointers Union variables may also be declared as an array or referenced using a pointer (in much the same way as structure arrays and pointers). [Union arrays] An array of unions is declared in the same ways as other objects. union data{ char name[12]; char addr[50]; char tel[12]; }; union data no[5];
[Union pointers] A pointer to a union has the characteristics of the union indicated by the pointer. In other words, if a union pointer is incremented, adding the size of the union to the pointer points to the next union. In the following example, "dt_p" is a pointer to the value of "union data" type. union data no[5]; union data *dt_p=no;
(4) How to refer to union members A union member (or union element) may be referenced in two ways: one by using a union variable and the other by using a pointer to a variable. [Reference by using a union variable] The . (dot) operator is used for referring to a union member by using a union variable. union data{ char name[12]; char addr[50]; char tel[12]; }no[5]={"NAME","ADDR","TEL"}; void main(void){ no[0].addr[10]='B'; . . . }
User's Manual U14872EJ1V0UM
135
CHAPTER 7
STRUCTURES AND UNIONS
[Reference by using a pointer to a variable] The -> (arrow) operator is used for referring to a union member by using a pointer to a variable. union data{ char name[12]; char addr[50]; char tel[12]; }data_ptr; void main(void){ data_ptr->name[1]='N'; . . . }
136
User's Manual U14872EJ1V0UM
CHAPTER 8
EXTERNAL DEFINITIONS
In a program, lists of external declarations come after the preprocessing. These declarations are referred to as "external declarations" because they appear outside a function and have valid file ranges. A declaration to give a name to external objects via an identifier or a declaration to secure storage for a function is called an external definition. If an identifier declared with external linkage is used in an expression (except the operand part of the sizeof operator), one external definition for the identifier must exist somewhere in the entire program. The syntax of external definitions is given below. #define TRUE #define SIZE 1 200
#define FALSE 0 void printf(char*,int); void putchar(char c); char mark[SIZE+1]; main() { int i,prime,k,count; count=0; for(i=0;i<=SIZE;i++) mark[i]=TRUE; for(i=0;i<=SIZE;i++){ if(mark[i]){ prime=i+i+3; printf("%d",prime); count++; if((count%8)==0) putchar('\n'); for(k=i+prime;k<=SIZE;k+=prime) mark[k]=FALSE; } } printf("Total %d\n",count); loop1: goto loop1; } External object definition
User's Manual U14872EJ1V0UM
137
CHAPTER 8
EXTERNAL DEFINITIONS
8.1
Function Definitions
A function definition is an external definition that begins with a declaration of the function. If the storage class specifier is omitted from the declaration, extern is assumed to have been defined. An external function definition means that the defined function may be referenced from other files. For example, in a program consisting of two or more files, if a function in another file is to be referenced, this function must be defined externally. The storage class specifier of an external function is extern or static. If a function is declared as extern, the function can be referenced from another file. If declared as static, it cannot be referenced from another file. In the following example, the storage class specifier is "extern" and the type specifier is "int". These two are default values and thus may be omitted. The function declarator is "max(int a, int b)" and the body of the function is "{return a>b?a:b;)". [Example of function definition] extern int max(int a, int b) { return a > b ? a : b; }
Because this function definition specifies a parameter type in the function declaration, the type of argument is forcibly converted by the compiler. This type conversion can be described by using the form of an identifier list for the parameters. An example of this identifier list is shown below. extern int max(a, b) int a, b; { return a > b ? a : b; }
The address of the function may be passed as an argument to a function call. A pointer to the function can be generated by using the function name in the expression. int f(void); void main(){ . . . g(f); }
138
User's Manual U14872EJ1V0UM
CHAPTER 8
EXTERNAL DEFINITIONS
In the above example, the function g is passed to the function f by a pointer that points to the function f. The function g must be defined in either of the following two ways. void g(int(*funcp)(void)) { (*funcp)(); /* } or void g(int func(void)) { func(); /* } or (*func) ( );*/ or funcp( );*/
User's Manual U14872EJ1V0UM
139
CHAPTER 8
EXTERNAL DEFINITIONS
8.2
External Object Definitions
An external object definition refers to the declaration of an identifier for an object that has a file scope or initializer. If the declaration of an identifier for an object which has file scope has no initializer without a storage class specification or has the storage class static, the object definition is considered to be temporary, because it becomes a declaration which has file scope with initializer 0. Examples of external object definitions are shown below. [Example of external object definition] int i1=1; .............................. static int i2=2; ............... extern int i3=3; ............... int i4;................................... static int i5;.................... int i1;................................... int i2;................................... int i3;................................... int i4;................................... int i5;................................... extern int i1;.................... extern int i2;.................... extern int i3;.................... extern int i4;.................... extern int i5;.................... Definition with external linkage Definition with internal linkage Definition with external linkage Temporary definition with external linkage Temporary definition with internal linkage Valid temporary definition which refers to previous declaration Violation of linkage rule Valid temporary definition which refers to previous declaration Valid temporary definition which refers to previous declaration Violation of linkage rule Reference to previous declaration which has external linkage Reference to previous declaration which has internal linkage Reference to previous declaration which has external linkage Reference to previous declaration which has external linkage Reference to previous declaration which has internal linkage
140
User's Manual U14872EJ1V0UM
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
A preprocessing directive is a string of preprocessing tokens between the # preprocessing token and the line feed character. White-space characters that can be used between preprocessor token strings are only spaces and horizontal tabs. A preprocessing directive specifies the processing performed before compiling a source file. Preprocessing directives include such operations as processing or skipping a part of a source file depending on the condition, obtaining additional code from other source files, and replacing the original source code with other text as in macro expansion. The preprocessing directives are explained in the following pages.
User's Manual U14872EJ1V0UM
141
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
9.1
Conditional Inclusion
Conditional inclusion skips part of a source file according to the value of a constant expression. If the value of the constant expression specified by a conditional inclusion directive is 0, the statements that follow the directive are not translated (compiled). The sizeof operator, cast operator, or an enumerated type constant cannot be used in the constant expression of any conditional inclusion directive. Conditional inclusion directives include #if, #elif, #ifdef, #ifndef, #else, and #endif. In preprocessing directives, the following unary expressions called defined expressions may be used. defined identifier defined (identifier)
The unary expressions return 1 if the identifier has been defined with the #define preprocessing directive and 0 if the identifier has never been defined or its definition has been canceled. [Example] In this example, the unary expression returns 1 and compiles between #if and #endif because SYM has been defined (for the explanation of #if through #endif, refer to the explanations in the following pages). #define SYM 0 #if defined SYM . . . #endif
142
User's Manual U14872EJ1V0UM
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(1) #if directive
Conditional Inclusion
#if
FUNCTION The #if directive tells the translation phase of C to skip (discard) a section of source code if the value of the constant expression is 0. SYNTAX #if constant expression new-line group
EXAMPLE #if FLAG==0 . . . #endif
EXPLANATION In the above example, the constant expression "FLAG == 0" is evaluated to determine whether a set of statements (i.e., source code) between #if and #endif is to be used in the translation phase. If the value of "FLAG" is nonzero, the source code between #if and #endif will be discarded. If the value is zero, the source code between #if and #endif will be translated.
User's Manual U14872EJ1V0UM
143
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(2) #elif directive
Conditional Inclusion
#elif
FUNCTION The #elif directive normally follows the #if directive. If the value of the constant expression of the #if directive is 0, the constant expression of the #elif directive is evaluated. If the constant expression of the #elif directive is 0, the translation phase of C will skip (discard) the statements (a section of source code) between #elif and #endif. SYNTAX #elif constant-expression new-line group
EXAMPLE #if FLAG==0 . . . #elif FLAG!=0 . . . #endif
EXPLANATION In the above example, the constant expression "FLAG= =0" or "FLAG!=0" is evaluated to determine whether a set of statements that follow #if and another set of statements that follow #elif are to be used in the translation phase. If the value of "FLAG" is zero, the source code between #if and #elif will be translated. If the value is nonzero, the source code between #elif and #endif will be translated.
144
User's Manual U14872EJ1V0UM
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(3) #ifdef directive
Conditional Inclusion
#ifdef
FUNCTION The #ifdef directive is equivalent to: #if defined (identifier) If the identifier has been defined with the #define directive, the statements between #ifdef and #endif will be translated. If the identifier has never been defined or its definition has been canceled, the translation phase will skip the source code between #ifdef and #endif. SYNTAX #ifdef identifier new-line group
EXAMPLE #define ON #ifdef ON . . . #endif
EXPLANATION In the above example, the identifier "ON" has been defined with the #define directive. Thus, the source code between #ifdef and #endif will be translated. If the identifier "ON" has never been defined, the source code between #ifdef and #endif will be discarded.
User's Manual U14872EJ1V0UM
145
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(4) #ifndef directive
Conditional Inclusion
#ifndef
FUNCTION The #ifndef directive is equivalent to: #if !defined (identifier) If the identifier has never been defined with the #define directive, the source code between #ifndef and #endif will not be translated. SYNTAX #ifndef identifier new-line group EXAMPLE #define ON #ifndef ON . . . #endif
EXPLANATION In the above example, the identifier "ON" has been defined with the #define directive. Thus, the program between #ifndef and #endif will not be translated. If the identifier "ON" has never been defined, the program between #ifndef and #endif will be translated.
146
User's Manual U14872EJ1V0UM
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(5) #else directive
Conditional Inclusion
#else
FUNCTION The #else directive tells the translation phase of C to discard a section of source code that follows #else if the identifier of the preceding conditional inclusion directive is nonzero. The #if, #elif, #ifdef, or #ifndef directive may precede the #else directive. SYNTAX #else new-line group
EXAMPLE #define ON #ifdef ON . . . #else . . . #endif
EXPLANATION In the above example, the identifier "ON" has been defined with the #define directive. Thus, the source code between #ifndef and #endif will be translated. If the identifier "ON" has never been defined, the source code between #else and #endif will be translated.
User's Manual U14872EJ1V0UM
147
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(6) #endif directive
Conditional Inclusion
#endif
FUNCTION The #endif directive indicates the end of a #ifdef block. SYNTAX #endif new-line
EXAMPLE #define ON #ifdef ON . . . #endif
EXPLANATION In the above example, #endif indicates the end of the #ifdef block (effective range of #ifdef directive).
148
User's Manual U14872EJ1V0UM
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
9.2
Source File Inclusion
The preprocessing directive #include searches for a specified header file and replaces the #include directive with the entire contents of the header file. The #include directive may take one of the following three forms for inclusion of other source files. * #include * #include "file-name" * #include preprocessing token string An #include directive may appear in the source obtained by #include. In this compiler, however, there are restrictions for #include directive nesting. Characteristics of This C Compiler. Remark Preprocessor token string: Character string defined by the #define directive For the restrictions, refer to Table 1-1 Maximum Performance
User's Manual U14872EJ1V0UM
149
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(1) #include < > directive
Source File Inclusion
#include< >
FUNCTION If the directive form is #include < >, the C compiler searches the directory specified by the -i compiler option, directory specified by the INC78K environment variable, and directory \NECTools32\INC78K0S registered in the registry for the header file specified in angle brackets and replaces the #include directive line with the entire contents of the specified file. SYNTAX #include new-line
EXAMPLE #include
EXPLANATION In the above example, the C compiler searches the directory specified by the INC78K environment variable and directory \NECTools32\INC78K0S registered in the registry for the file stdio.h and replaces the directive line #include with the entire contents of the specified file stdio.h. Caution The above directories differ depending on the installation method.
150
User's Manual U14872EJ1V0UM
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(2) #include " " directive
Source File Inclusion
#include " "
FUNCTION If the directive form is #include " ", the current working directory is first searched for the header file specified in double quotes. If it is not found, the directory specified by the -i compiler option, directory specified by the INC78K environment variable, and directory \NECTools32\INC78K0S registered in the registry is searched. Then, the compiler replaces the #include directive line with the entire contents of the specified file thus searched. SYNTAX #include "file-name" new-line
EXAMPLE #include "myprog.h"
EXPLANATION In the above example, the C compiler searches the current working directory, the directory specified by the INC78K environment variable, and directory \NECTools32\INC78K0S registered in the registry for the file myprog.h specified in double quotes and replaces the directive line #include "myprog.h" with the entire contents of the specified file myprog.h. Caution The above directories differ depending on the installation method.
User's Manual U14872EJ1V0UM
151
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(3) #include preprocessing token string directive
Source File Inclusion
#include token string
FUNCTION If the directive form is #include preprocessing token string, the header file to be searched is specified by macro replacement and the #include directive line is replaced by the entire contents of the specified file. SYNTAX #include preprocessing token string new-line
EXAMPLE #define INCFILE "myprog.h" #define INCFILE
EXPLANATION In the inclusion of other source files with the directive form #include preprocessing token string, the specified "preprocessing token string" must be replaced by or "file name" using macro replacement. If the token string is replaced by , the C compiler searches the directory specified by the -i compiler option, directory specified by the INC78K environment variable, and directory \NECTools32\INC78K0S registered in the registry for the specified file. If the token string is replaced by "file name", the current working directory is searched. If the specified file is not found, the directory specified by the -i compiler option, directory specified by the INC78K environment variable, and directory \NECTools32\INC78K0S registered in the registry is searched.
152
User's Manual U14872EJ1V0UM
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
9.3
Macro Replacement
The macro replacement directives #define and #undef are used to replace the character string (macro name) specified by the identifier with "substitution list". The #define directive has two forms: object format and function format: * Object format #define identifier replacement-list new-line * Function format #define identifier ( identifier-list ) replacement-list new-line
(1) Actual argument replacement Actual argument replacement is executed after the arguments in the function-form macro call are identified. If the # or ## preprocessing token is not prefixed to a parameter in the replacement list or if the ## preprocessing token does not follow any such parameter, all macros in the list will be expanded before replacement with the corresponding macro arguments. (2) # operator The # preprocessing token replaces the corresponding macro argument with a char string processing token. In other words, if this preprocessing token is prefixed to a parameter in the replacement list, the corresponding macro argument will be translated into a character or character string. (3) ## operator The ## preprocessing token concatenates the two tokens on either side of the ## symbol into one token. This concatenation will take place before the next macro expansion and the ## preprocessing token will be deleted after the concatenation. The token generated from this concatenation will undergo macro expansion if it has a macro name. [Example of ## operation] The above macro replacement directive will be expanded as follows. printf("x""1""=%d,x""2""=%s",x1,x2); The concatenated char string will look like this. printf("x1=%d,x2=%s",x1,x2);
#include #define debug(s, t) printf("x"#s"=%d, x"#t"=%s", x##s, x##t);
void main(){ int } x1, x2; debug (1, 2);
User's Manual U14872EJ1V0UM
153
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(4) Re-scanning and further replacement The preprocessing token string resulting from replacement of macro parameters in the list will be scanned again, together with all remaining preprocessing tokens in the source file. Macro names currently being replaced (not including the remaining preprocessing tokens in the source file) will not be replaced even if they are found during scanning of the replacement list. (5) Scope of macro definition A macro definition (#define directive) continues macro replacement until it encounters the corresponding #undef directive.
154
User's Manual U14872EJ1V0UM
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(6) #define directive
Macro Replacement
#define
FUNCTION The #define directive in its simplest form replaces the specified identifier with a given replacement list whenever the same identifier appears in the source code after the definition by this directive. SYNTAX #define identifier replacement-list new-line
EXAMPLE #define PAI 3.1415
EXPLANATION In the above example, the identifier "PAI" will be replaced with "3.1415" whenever it appears in the source code after definition by this directive.
User's Manual U14872EJ1V0UM
155
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(7) #define ( ) directive
Macro Replacement
#define ( )
FUNCTION The function-form #define directive replaces the identifier specified in the function format with a given replacement list whenever the same identifier appears in the source code after definition by this directive. Function-form macro replacement also includes replacing argument. SYNTAX #define identifier ( identifier list ) replacement-list new-line
EXAMPLE #define F(n) (n*n) void main(){ int i; i=F(2) }
EXPLANATION In the above example, #define directive will replace "F(2)" with "(2*2)" and thus the value of i will become 4. For the sake of safety, be sure to enclose the replacement list in parentheses, because unlike a function definition, this function-form macro merely replaces a sequence of characters.
156
User's Manual U14872EJ1V0UM
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
(8) #undef directive
Macro Replacement
#undef
FUNCTION The #undef directive ends the scope of the identifier that has been set by the corresponding #define directive. SYNTAX #undef identifier new-line
EXAMPLE #define F(n) (n*n) . . . #undef F
EXPLANATION In the above example, the #undef directive will invalidate the identifier "F" previously specified by "#define F(n) (n*n)".
User's Manual U14872EJ1V0UM
157
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
9.4
Line Control
The preprocessing directive for line control #line replaces the line number to be used by the C compiler in translation with the number specified by this directive. If a string (character string) is given in addition to the number, the directive also replaces the source file name the C compiler has with the specified string. (1) To change the line number To change the line number, the specification is made as follows. 0 and numbers larger than 32767 cannot be specified. #line numeric-string new-line
[Example] #line 10
(2) To change the line number and the file name To change the line number and file name, the specification is made as follows. #line numeric-string "character string" new-line
[Example] #line 10 "file1.c"
(3) To change using preprocessor token string In addition to the specifications above, the following specification can also be made. In this case, the specified preprocessing token string must be either one of the above two examples after all the replacement. #line preprocessing-token-string new-line
[Example] #define LINE_NUM 100 #line LINE_NUM
158
User's Manual U14872EJ1V0UM
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
9.5
#error Preprocessing Directive
The #error preprocessing directive is a directive that outputs a message including the specified preprocessing tokens and incompletely terminates a compile. This preprocessing is used to terminate a compile. This preprocessing is specified as follows. #error "preprocessing-token-string" new-line
[Example] In this example, the macro name _ _K0S _ _, which indicates the device series that this compiler has, is used. If the device is the 78K/0S Series, the program between #if and #else is compiled. In the other cases, the program between #else and #endif is compiled, but the compilation will be terminated with an error message "not for 78K0S" output by #error directive. #if _ _K0S_ _ . . . #else #error "not for 78K0S" . . . #endif
User's Manual U14872EJ1V0UM
159
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
9.6
#pragma Directive
The #pragma directive is a directive to instruct the compiler to operate using the compiler definition method. In this compiler, there are several #pragma directives to generate codes for the 78K/0S Series (For details of the #pragma directives, refer to CHAPTER 11 EXTENDED FUNCTIONS). [Example] In this example, the #pragma NOP directive enables the description to directly output a NOP instruction in the C source. #pragma NOP
9.7
Null Directive
Source lines that contain only the # character and white space are called null directives. Null directives are simply discarded during preprocessing. In other words, these directives have no effect on the compiler. The syntax of null directives is given below. # new-line
160
User's Manual U14872EJ1V0UM
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
9.8
Predefined Macro Names
In this C compiler, the following macro names have been defined. _ _LINE_ _ _ _FILE_ _ _ _DATE_ _ _ _TIME_ _ _ _STDC_ _ Line number of the current source line (decimal constant) Source file name (string literal) Date the source file was compiled (string literal in the form of "Mmm dd yyyy") Time of day the source file was compiled (string literal in the form of "hh:mm:ss") Decimal constant "1" that indicates the compliance with ANSI
Note
specification
Note ANSI is the acronym for American National Standards Institute A #define or #undef preprocessing directive must not be applied to these macro names and defined identifiers. All the macro names of the compiler definition start with an underscore followed by an uppercase character or a second underscore. In addition to the above macro names, macro names indicating the series names of devices depending on the device subject to applied product development and macro names indicating device names are provided. To output the object code for the target device, these macro names must be specified by the option at compilation time or by the processor type in the C source. * Macro name indicating the series names of devices '_ _K0S_ _' * Macro name indicating the device name `_ _' is added before the device type name and `_' is added after the device type name. Describe English characters in uppercase. (Example) _ _9026_ _ _9216Y_
Remark
The device type names are the same as the ones specified by -C option. For the device type names, refer to the reference related to device files.
This C compiler has a macro name indicating the memory model. * Define as follows when the static model is specified #define _ _STATIC_MODEL_ _ 1
The device type for compilation is specified by adding the following to the command line `-c device type name' (Example) cc78ks -c9216Y prime.c
User's Manual U14872EJ1V0UM
161
CHAPTER 9
PREPROCESSING DIRECTIVES (COMPILER DIRECTIVES)
The device type does not need to be specified on compilation by specifying it at the start of the C source program. `#pragma PC (device type)' (Example) #pragma PC(9216Y) . . .
However, the following can be described before `#pragma PC (device type)' * Comment statement * Preprocessing directives that do not generate a definition/reference of variables nor functions.
162
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
C has no instructions to transfer (input or output) data to and from external sources (peripheral devices and equipment). This is because of the C language designer's intent to hold the functions of C to a minimum. However, for actually developing a system, I/O operations are requisite. Thus, C is provided with library functions to perform I/O operations. This C compiler is provided with library functions such as I/O, character/memory manipulation, program control, and mathematical functions. This chapter describes the library functions provided in this compiler.
User's Manual U14872EJ1V0UM
163
CHAPTER 10
LIBRARY FUNCTIONS
10.1 Interface Between Functions
To use a library function, the function must be called. Calling a library function is carried out by a call instruction. The arguments and return value of a function are passed by a stack and a register, respectively. However, when the old function interface supporting option (-ZO) is not specified in the normal model, the first argument is, if possible, also passed by the register. In addition, all of the arguments are passed by the register in the static model. For the -ZO option, refer to the CC78K0S C Compiler Operation User's Manual (U14871E) CHAPTER 5 COMPILER OPTION. 10.1.1 Arguments Placing or removing arguments on or from the stack is performed by the caller (calling side). The callee (called side) only references the argument values. However, when the argument is passed by the register, the callee directly refers to the register and copies the value of the argument to another register, if necessary. Also, when specifying the function call interface automatic pascal function option -ZR, removal of arguments from the stack is performed by the called side if the argument is passed on the stack. Arguments are placed on the stack one by one in descending order from last to top if the argument is passed on the stack. The minimum unit of data that can be stacked is 16 bits. A data type larger than 16 bits is stacked in units of 16 bits one by one from its MSB. An 8-bit type data is extended to a 16-bit type data for stacking. For the static model, all of arguments are passed by a register. A maximum of 3 arguments and a total of 6 bytes can be passed. Passing float, double, and structure arguments is not supported. Lists of argument passing are shown below. The second argument and thereafter is passed via a stack in the normal model. The function interface (passing of argument and storing of return value) of the standard library is the same as that of a normal function. Table 10-1. List of Passing First Argument (Normal Model)
Type of First Argument 1-byte, 2-byte integers 3-byte integer 4-byte integer Floating-point number (float type) Floating-point number (double type) Others AX AX, BC AX, BC AX, BC Passing Method
AX, BC Passed via a stack
Remark
Of the types shown above, 1- to 4-byte integers include structures and unions.
164
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
Table 10-2. List of Passing Arguments (Static Model)
Type of Argument 1-byte integer 2-byte integer A AX 1st Argument B BC 2nd Argument H HL 3rd Argument
Remark
If the arguments are a total of 4 bytes, some of the arguments are allocated to AX and BC, and the rest to HL or H. 1- to 4-byte integers do not include structures and unions.
10.1.2 Return values The return value of a function is stored in units of 16 bits starting from its LSB in the direction from register BC to register DE. When returning a structure, the first address of the structure is stored in register BC. When returning a pointer, the first address of the structure is stored in register BC. The following shows a list of the storing of the return value. The method of storing return values is the same as that of normal function. Table 10-3. List of Storing Return Value (1) Normal model
Type of Return Value 1 bit 1-byte, 2-byte integers 4-byte integer Floating-point number (float type) Floating-point number (double type) Structure CY BC BC (lower), DE (higher) BC (lower), DE (higher) BC (lower), DE (higher) Copies the structure to return to the area specific to the function and stores the address to BC BC Method of Storing
Pointer
(2) Static model
Type of Return Value 1 bit 1-byte integer 2-byte integer 4-byte integer Pointer CY A AX AX (lower), BC (higher) AX Method of Storing
10.1.3 Saving registers to be used by individual libraries Libraries that use HL (normal model) and DE (static model) save the registers used to a stack. Libraries that use saddr area save the saddr area used to a stack. A stack area is used as a work area for each library.
User's Manual U14872EJ1V0UM
165
CHAPTER 10
LIBRARY FUNCTIONS
(1) No -ZR option specified The procedure of passing arguments and return values is shown below. Called function "long func(int a, long b, char *c);"
<1> Placing arguments on the stack (by the caller) The higher 16 bits of arguments "c" and "b" and lower 16 bits of argument "b" are placed on the stack in the order named. a is passed by the AX register. <2> Calling func by call instruction (by the caller) The return address is placed on the stack next to the lower 16 bits of argument "b" and control is transferred to the function func. <3> Saving registers to be used within the function (by the callee) If register HL is to be used, HL is placed on the stack. <4> Placing the first argument passed by the register on the stack (by the callee) <5> Processing func and storing the return value in registers (by the callee) The lower 16 bits of the return value "long" are stored in BC and the higher 16 bits of the return value in DE. <6> Restoring the stored first argument (by the callee) <7> Restoring the saved registers (by the callee) <8> Returning control to the caller with ret instruction (by the callee) <9> Removing arguments from the stack (by the caller) The number of bytes (in units of 2 bytes) of the arguments is added to the stack pointer. In the example shown in Figure 10-1, 6 is added.
166
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
Figure 10-1. Stack Area When Function Is Called (No -ZR Specified)
Return value in <5> is stored Lower 16 bits Higher 16 bits
BC Stack pointer after <4> Stack pointer after <3> Stack pointer after <2> Stack pointer after <1> a HL Return address Lower 16 bits of b Upper 16 bits of b c Stack pointer before stacking arguments Stack pointer after <9> Stack pointer after <6> Stack pointer after <7> Stack pointer after <8>
DE
High address
(2) -ZR option specified The following example shows the procedure of passing arguments and return values when the -ZR option is specified. Called function "long func(int a, long b, char *c);"
<1> Placing arguments on the stack (by the caller) The higher 16 bits of arguments "c" and "b" and the lower 16 bits of argument "b" are placed on the stack in that order. a is passed by the AX register.
Low address
Stack pointer
Lower 16 bits of b Higher 16 bits of b c
Stack pointer before stacking arguments High address
User's Manual U14872EJ1V0UM
167
CHAPTER 10
LIBRARY FUNCTIONS
<2> Calling func by a call instruction (by the caller) Control is transferred to the function func when the stack is in the state shown below.
Low address Stack pointer
Return Lower 16 bits of b Higher 16 bits of b c
High address
<3> Saving the register used (by the callee)
Low address Stack pointer Stack pointer when called
HL Return Lower 16 bits of b Higher 16 bits of b c
High address
<4> The first argument called by the register is placed on the stack
Low address Stack pointer
a HL Return Lower 16 bits of b Higher 16 bits of b c
High address
168
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
<5> Performing processing of the function func, and storing return values in the register (by the callee) The lower 16 bits of the return value are stored in BC and the higher 16 bits are stored in DE.
BC Lower 16 bits of return value DE Higher 16 bits of return value
<6> Restoring the first placed argument (by the callee)
Low address Stack pointer
HL Return Lower 16 bits of b Higher 16 bits of b c
High address
<7> Restoring the saved registers (by the callee)
Low address Stack pointer
Return Lower 16 bits of b Higher 16 bits of b c
High address
<8> Storing the return address in the register and removing the arguments from the stack by shifting the stack pointer to the position before arguments were placed.
Low address Stack pointer
Return Lower 16 bits of b Higher 16 bits of b c
High address
User's Manual U14872EJ1V0UM
169
CHAPTER 10
LIBRARY FUNCTIONS
<9> Restoring the return address stored in the register (by the callee)
Low address
Return
Stack pointer before arguments were stacked High address
Stack pointer
<10> Returning control to the functions on the caller by the ret instruction (by the callee)
Low address Stack pointer before arguments were stacked High address Stack pointer
170
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
10.2 Headers
This C compiler has 13 headers (or header files). Each header defines or declares standard library functions, data type names, and macro names. The headers of this C compiler are as shown below. ctype.h stdlib.h limits.h assert.h Caution The functions to be supported differ depending on the memory models (normal model and static model). Also, functions that operate during normal operation differ depending on the -ZI and -ZL options. For functions that do not operate normally because of the existence of -ZI and -ZL options, a warning message "The prototype declaration is not performed" is output. setjmp.h string.h stddef.h stdarg.h error.h math.h stdio.h errno.h float.h
User's Manual U14872EJ1V0UM
171
CHAPTER 10
LIBRARY FUNCTIONS
(1) ctype.h This header is used to define character and string functions. In this standard header, the following library functions have been defined. However, when the compiler option -ZA (the option that disables the functions not compliant with ANSI specifications and enables a part of the functions of ANSI specifications) is specified, _toupper and _tolower are not defined. Instead, tolow and toup are defined. When -ZA is not specified, tolow and toup are not defined. The function to be declared differs depending on the options and the specification models. Table 10-4. Contents of ctype.h
Existence of -ZI, or -ZL Specification Function Name isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper isascii toascii _toupper _tolower tolow toup Normal Model None ZI ZL ZI ZL None Static Model ZI -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ZL ZI ZL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
: Supported --: Not supported
172
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
(2) setjmp.h This header is used to define program control functions. In this header, the following functions are defined. The function to be declared differs depending on the option and the specification models. Table 10-5. Contents of setjmp.h
Existence of -ZI, or -ZL Specification Function Name setjmp longjmp Normal Model None ZI ZL ZI ZL None Static Model ZI -- -- ZL ZI ZL -- --
: Supported --: Not supported In the header setjmp.h, the following object has been defined. [Declaration of int array type jmp_buf] * Normal model typedef int jmp_buf[11]; * Static model typedef int jmp_buf[3];
User's Manual U14872EJ1V0UM
173
CHAPTER 10
LIBRARY FUNCTIONS
(3) stdarg.h (normal model only) This header used to define special functions. In this header, the following three functions have been defined. Table 10-6. Contents of stdarg.h
Existence of -ZI, or -ZL Specification Function Name va_arg va_start va_end Normal Model None ZI ZL ZI ZL
: Supported : Operation is guaranteed, however there are limitations
In the header stdarg.h the following object has been declared. [Declaration of pointer type va_list to char] typedef char *va_list;
(4) stdio.h This header is used to define I/O functions. In this header, next functions have been defined. The function to be declared differs depending on the options and the specification models. Table 10-7. Contents of stdio.h
Existence of -ZI, or -ZL Specification Function Name sprintf sscanf printf scanf vprintf vsprintf getchar gets putchar puts x x x x x x Normal Model None ZI ZL ZI ZL x x x x x x None -- -- -- -- -- -- Static Model ZI -- -- -- -- -- -- -- -- -- ZL -- -- -- -- -- -- ZI ZL -- -- -- -- -- -- -- -- --
: Supported x: Operation is not guaranteed --: Not supported The following macro names are declared. #define EOF (-1)
#define NULL (void *)0
174
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
(5) stdlib.h This header is used to define character and string functions, memory functions, program control functions, mathematical functions, and special functions. In this standard header, the following library functions have been defined. However, when the compiler option -ZA (the option that disables the functions not compliant with ANSI specifications and enables a part of the functions of ANSI specifications) is specified, brk, sbrk, itoa, ltoa, and ultoa are not defined. Instead, strbrk, strsbrk, stritoa, strltoa, and strultoa are defined. When -ZA is not specified, these functions are not defined. Table 10-8. Contents of stdlib.h
Existence of -ZI, or -ZL Specification Function Name atoi atol strtol strtoul calloc free malloc realloc abort atexit exit abs div labs ldiv brk sbrk atof strtod itoa ltoa ultoa rand srand bsearch qsort strbrk strsbrk stritoa strltoa strultoa x -- x x x x x -- -- -- -- -- Normal Model None ZI ZL ZI ZL x x x x -- x -- -- -- x -- -- None -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Static Model ZI -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ZL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ZI ZL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
: Supported x: Operation is not guaranteed --: Not supported In the header stdlib.h the following objects have been defined.
User's Manual U14872EJ1V0UM
175
CHAPTER 10
LIBRARY FUNCTIONS
[Declaration of structure type div_t which has int type members quot and rem (except static model)] typedef struct{ int quot; int rem; }div_t;
[Declaration of structure type ldiv_t which has long int type members quot and rem (except when -ZL is specified in static model and normal model)] typedef struct{ long int quot; long }ldiv_t; int rem;
[Definition of macro name RAND_MAX] #define RAND_MAX 32767
[Declaration of macro name] define EXIT_SUCCESS 0 define EXIT_FAILURE 1
176
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
(6) string.h This header is used to define character and string functions, memory functions, and special functions. In this header, the following functions have been defined. The function to be defined differs depending on the options and specification models. Table 10-9. Contents of string.h
Existence of -ZI, or -ZL Specification Function Name memcpy memmove strcpy strncpy strcat strncat memcmp strcmp strncmp memchr strchr strcspn strpbrk strrchr strspn strstr strtok memset strerror strlen strcoll strxfrm x x x x x x x x Normal Model None ZI ZL ZI ZL x x x x x x x x None Static Model ZI -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ZL ZI ZL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
: Supported x: Operation is not guaranteed --: Not supported
User's Manual U14872EJ1V0UM
177
CHAPTER 10
LIBRARY FUNCTIONS
(7) error.h error.h includes errno.h. (8) errno.h In this header, the following objects have been defined. [Definitions of macro names "EDOM", "ERANGE", and "ENOMEM"] #define EDOM 1
#define ERANGE 2 #define ENOMEM 3 [Declaration of volatile int type external variable errno] extern volatile int errno;
(9) limits.h In this header, the following macro names have been defined. #define CHAR_BIT #define CHAR_MAX #define CHAR_MIN #define INT_MAX #define INT_MIN #define LONG_MAX #define LONG_MIN #define SCHAR_MAX #define SCHAR_MIN #define SHRT_MAX #define SHRT_MIN #define UCHAR_MAX #define UINT_MAX #define ULONG_MAX #define USHRT_MAX #define SINT_MAX #define SINT_MIN #define SSHRT_MAX #define SSHRT_MIN 8 +127 -128 +32767 -32768 +2147483647 -2147483648 +127 -128 +32767 -32768 255U 65535U 4294967295U 65535U +32767 -32768 +32767 -32768
However, when the -QU option, which regards unqualified char as unsigned char, is specified, CHAR_MAX and CHAR_MIN are declared as follows, via the macro _ _CHAR_UNSIGNED_ _ declared by the compiler. #define CHAR_MAX #define CHAR_MIN (255U) (0)
178
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
When the -ZI option (int and short types are regarded as char type, unsigned int and unsigned short as unsigned char) is specified as a compiler option, INT_MAX, INT_MIN, SHRT_MAX, SHRT_MIN, SINT_MAX, SINT_MIN, SSHRT_MAX, SSHRT_MIN, UINT_MAX, and USHRT_MAX are declared as follows, via the macro _ _FROM_INT_TO_CHAR_ _ declared by the compiler. #define INT_MAX #define INT_MIN #define SHRT_MAX #define SHRT_MIN #define SINT_MAX #define SINT_MIN #define SSHRT_MAX #define SSHRT_MIN #define UINT_MAX #define USHRT_MAX CHAR_MAX CHAR_MIN CHAR_MAX CHAR_MIN SCHAR_MAX SCHAR_MIN SCHAR_MAX SCHAR_MIN UCHAR_MAX UCHAR_MIN
When the -ZL option (long type is regarded as int type and unsigned long as unsigned int) is specified as a compiler option, LONG_MAX, LONG_MIN, and ULONG_MAX are declared as follows, via the macro _ _FROM_LONG_TO_INT_ _ declared by the compiler. #define LONG_MAX #define LONG_MIN #define ULONG_MAX (+32767) (-32768) (65535U)
User's Manual U14872EJ1V0UM
179
CHAPTER 10
LIBRARY FUNCTIONS
(10) stddef.h In this header, the following objects have been declared and defined. [Declaration of int type ptrdiff_t] typedef int ptrdiff_t;
[Declaration of unsigned int type size_t] typedef unsigned int size_t;
[Definition of macro name NULL] #define NULL (void*)0;
[Definition of macro name offsetof] #define offsetof(type, member) ((size_t)&(((type*)0)->member)) * offsetof (type, member specifier) offsetof is expanded to the general integer constant expression that has type size_t and the value is an offset value in byte units from the start of the structure (that is specified by the type) to the structure member (that is specified by the member specifier). The member specifier must be the one that the result of evaluation of the expression & (t. member specifier) becomes an address constant when static type t; is declared. When the specified member is a bit field, the operation will not be guaranteed.
180
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
(11) math.h (normal model only) math.h defines the following functions. Table 10-10. Contents of math.h (1/2)
Existence of -ZI, or -ZL Specification Function Name acos asin atan atan2 cos sin tan cosh sinh tanh exp frexp ldexp log log10 modf pow sqrt ceil fabs floor fmod matherr acosf asinf atanf atan2f cosf sinf tanf coshf sinhf tanhf expf frexpf ldexpf logf log10f modff -- Normal Model None ZI ZL ZI ZL --
: Supported --: Not supported
User's Manual U14872EJ1V0UM
181
CHAPTER 10
LIBRARY FUNCTIONS
Table 10-10. Contents of math.h (2/2)
Existence of -ZI, or -ZL Specification Function Name powf sqrtf ceilf fabsf floorf fmodf Normal Model None ZI ZL ZI ZL
: Supported The following objects are defined. [Definition of macro name HUGE_VAL] #define HUGE_VAL DBL_MAX
182
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
(12) float.h float.h defines the following objects. When the size of a double type is 32 bits, the macros to be defined are sorted by the macro _ _DOUBLE_IS_32BITS_ _ declared by the compiler. #ifndef _FLOAT_H #define FLT_ROUNDS #define FLT_RADIX #ifdef _ _DOUBLE_IS_32BITS_ _ #define FLT_MANT_DIG #define DBL_MANT_DIG #define LDBL_MANT_DIG #define FLT_DIG #define DBL_DIG #define LDBL_DIG #define FLT_MIN_EXP #define DBL_MIN_EXP #define LDBL_MIN_EXP #define FLT_MIN_10_EXP #define DBL_MIN_10_EXP #define LDBL_MIN_10_EXP #define FLT_MAX_EXP #define DBL_MAX_EXP #define LDBL_MAX_EXP #define FLT_MAX_10_EXP #define DBL_MAX_10_EXP #define LDBL_MAX_10_EXP #define FLT_MAX #define DBL_MAX #define LDBL_MAX #define FLT_EPSILON #define DBL_EPSILON #define LDBL_EPSILON #define FLT_MIN #define DBL_MIN #define LDBL_MIN 24 24 24 6 6 6 -125 -125 -125 -37 -37 -37 +128 +128 +128 +38 +38 +38 3.40282347E+38F 3.40282347E+38F 3.40282347E+38F 1.19209290E-07F 1.19209290E-07F 1.19209290E-07F 1.1749435E-38F 1.17549435E-38F 1.17549435E-38F 1 2
User's Manual U14872EJ1V0UM
183
CHAPTER 10
LIBRARY FUNCTIONS
#else
/* _ _DOUBLE_IS_32BITS_ _ */ 24 53 53 6 15 15 -125 -1021 -1021 -37 -307 -307 +128 +1024 +1024 +38 +308 +308 3.40282347E+38F 1.7976931348623157E+308 1.7976931348623157E+308 1.19209290E-07F 2.2204460492503131E-016 2.2204460492503131E-016 1.17549435E-38F 2.225073858507201E-308 2.225073858507201E-308
#define FLT_MANT_DIG #define DBL_MANT_DIG #define LDBL_MANT_DIG #define FLT_DIG #define DBL_DIG #define LDBL_DIG #define FLT_MIN_EXP #define DBL_MIN_EXP #define LDBL_MIN_EXP #define FLT_MIN_10_EXP #define DBL_MIN_10_EXP #define LDBL_MIN_10_EXP #define FLT_MAX_EXP #define DBL_MAX_EXP #define LDBL_MAX_EXP #define FLT_MAX_10_EXP #define DBL_MAX_10_EXP #define LDBL_MAX_10_EXP #define FLT_MAX #define DBL_MAX #define LDBL_MAX #define FLT_EPSILON #define DBL_EPSILON #define LDBL_EPSILON #define FLT_MIN #define DBL_MIN #define LDBL_MIN #endif #define #endif
/* _ _DOUBLE_IS_32BITS_ _ */ _FLOAT_H /* !_FLOAT_H */
184
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
(13) assert.h (normal model only) Table 10-11. Contents of assert.h
Existence of -ZI, or -ZL Specification Function Name _ _assertfail Normal Model None ZI ZL ZI ZL
: Supported assert.h defines the following objects. #ifdef NDEBUG #define assert(p) ((void)0) #else extern int _ _assertfail(char*_ _msg, char*_ _cond, char*_ _file, int_ _line); #define assert(p) ((p) ? (void)0 : (void)_ _assertfail( \ "Assertion failed: #endif /* NDEBUG */ %s, file %s, line %d\n", #p, _ _FILE_ _, _ _LINE_ _))
However, if the assert.h header file references another macro, NDEBUG, which is not defined by the assert.h header file, and if NDEBUG is defined as a macro when the assert.h is captured to the source file, the assert.h header file simply declares the assert macro as: #define assert(p) ((void)0) and does not define _ _ assertfail.
10.3 Re-entrantability (Normal Model Only)
Re-entrant is a state where a function called from a program can be consecutively called from another program. The standard library of this compiler does not use static area allowing re-entrantability. Therefore, data in the storage area used by functions will not be destroyed by a call from another program. However, the functions shown in (1) to (3) are not re-entrant. (1) Functions that cannot be re-entranced setjmp, longjmp, atexit, exit (2) Functions that use the area secured in the startup routine div, ldiv, brk, sbrk, rand, srand, strtok (3) Functions that deal with floating-point numbers sprintf, sscanf, printf, scanf, vprintf, vsprintf
Note
, atof, strtod, all the mathematical functions
Note Among sprintf, sscanf, printf, scanf, vprintf, and vsprintf, functions that do not support floating-point numbers are re-entrant.
User's Manual U14872EJ1V0UM
185
CHAPTER 10
LIBRARY FUNCTIONS
10.4 Standard Library Functions
This section explains the standard library functions of this C compiler classified by function as follows. All standard library functions are supported even when the -ZF option is specified. * Item (1-x) * Item (2-x) * Item (3-x) * Item (4-x) * Item (5-x) * Item (6-x) * Item (7-x) * Item (8-x) Character and character string functions Program control functions Special functions I/O functions Utility functions Character string/memory functions Mathematical functions Diagnostic functions
186
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
1-1
is-
Character & String Functions
FUNCTION is- judges the type of character. HEADER ctype.h for all the character functions FUNCTION PROTOTYPE int is-(int c);
Function is-
Arguments c.. Character to be judged
Return Value 1 if character c is included in the character range. 0 if character c is not included in the character range.
EXPLANATION
Function isalpha isupper islower isdigit isalnum isxdigit isspace Character Range Alphabetic character A to Z or a to z Uppercase letters A to Z Lowercase letters a to z Numeric characters 0 to 9 Alphanumeric characters 0 to 9 and A to Z or a to z Hexadecimal numbers 0 to 9 and A to F or a to f White-space characters (space, tab, carriage return, new-line, vertical tab, and form-feed) Punctuation characters except white-space characters Printable characters Printable nonblank characters Control characters ASCII character set
ispunct isprint isgraph iscntrl isascii
User's Manual U14872EJ1V0UM
187
CHAPTER 10
LIBRARY FUNCTIONS
1-2
toupper tolower
Character & String Functions
FUNCTION The character functions toupper and tolower both convert one type of character to another. The toupper function returns the uppercase equivalent of c if c is a lowercase letter. The tolower function returns the lowercase equivalent of c if c is a uppercase letter. HEADER ctype.h FUNCTION PROTOTYPE int to-(int c);
Function toupper, tolower
Arguments c.. Character to be converted
Return Value Uppercase equivalent if c is a convertible character. Character "c" is returned unchanged if not convertible.
EXPLANATION toupper * The toupper function checks to see if the argument is a lowercase letter and if so converts the letter to its uppercase equivalent. tolower * The tolower function checks to see if the argument is a uppercase letter and if so converts the letter to its lowercase equivalent.
188
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
1-3
toascii
Character & String Functions
FUNCTION The character function toascii converts "c" to an ASCII code. HEADER ctype.h FUNCTION PROTOTYPE int toascii(int c);
Function toascii
Arguments c.. Character to be converted
Return Value Value obtained by converting the bits outside the ASCII code range of "c" to 0.
EXPLANATION The toascii function converts the bits (bits 7 to 15) of "c" outside the ASCII code range of "c" (bits 0 to 6) to "0" and returns the converted bit value.
User's Manual U14872EJ1V0UM
189
CHAPTER 10
LIBRARY FUNCTIONS
1-4
_toupper/toup _tolower/tolow
Character & String Functions
FUNCTION The character function _toupper/toup subtracts "a" from "c" and adds "A" to the result. The character function _tolower/tolow subtracts "A" from "c" and adds "a" to the result. (_toupper is exactly the same as toup, and _tolower is exactly the same as the tolow) Remark HEADER ctype.h FUNCTION PROTOTYPE int _to-(int c); a: Lowercase; A: Uppercase
Function _toupper toup
Arguments c.. Character to be converted
Return Value Value obtained by adding "A" to the result of subtracting "a" from "c" Value obtained by adding "a" to the result of subtracting "A" from "c"
_tolower tolow
Remark
a: Lowercase; A: Uppercase
EXPLANATION _toupper * The _toupper function is similar to toupper except that it does not test to see if the argument is a lowercase letter. _tolower * The _tolower function is similar to tolower, except it does not test to see if the argument is an uppercase letter.
190
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
2-1
setjmp longjmp
Program Control Functions
FUNCTION The program control function setjmp saves the environment information (current state of the program) when a call to this function is made. The program control function longjmp restores the environment information saved by setjmp. HEADER setjmp. h FUNCTION PROTOTYPE int setjmp(jmp_buf env); void longjmp(jmp_buf env,int val);
Function setjmp
Arguments env ... Array to which environment information is to be saved
Return Value * 0 if called directly * Value given by "val" if returning from the corresponding longjmp or 1 if "val " is 0
longjmp
env ... Array to which environment information was saved by setjmp val ... Return value to setjmp
longjmp will not return because program execution resumes at statement next to setjmp that saved environment to "env".
EXPLANATION setjmp * setjmp, when called directly, saves the saddr area, SP, and the return address of the function, which are used as the HL register or register variables, to env and returns 0. longjmp * The longjmp restores the saved environment to env (saddr area and SP used as HL register or register variables). Program execution continues as if the corresponding setjmp returns val (however, if val is 0, 1 is returned).
User's Manual U14872EJ1V0UM
191
CHAPTER 10
LIBRARY FUNCTIONS
3-1
va_start (normal model only) va_arg (normal model only) va_end (normal model only)
Special Functions
FUNCTION The va_start function (macro) is used to start a variable argument list. The va_arg function (macro) obtains the value of an argument from a variable argument list. The va_end function (macro) indicates that the end of a variable argument list is reached. HEADER stdarg. h FUNCTION PROTOTYPE void va_start(va_list ap,parmN); type va_arg(va_list ap,type); void va_end(va_list ap);
Function va_start
Arguments ap ... Variable to be initialized so as to be used in va_arg and va_end parmN ... The argument before variable argument None
Return Value
va_arg
ap ... Variable to process an argument list type... Type to point the relevant place of variable argument (type is a type of variable length; for example, int type if described as va_arg (va_list ap, int) or long type if described as va_arg (va_list ap, long))
Normal case ... Value in the relevant place of variable argument If ap is a null pointer ... 0
va_end
ap .... Variable to process the variable number of arguments
None
192
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
va_start (normal model only) va_arg (normal model only) va_end (normal model only)
EXPLANATION va_start
Special Functions
* In the va_start macro, the argument ap must be a va_list type (char* type) object. * A pointer to the next argument of parmN is stored in ap. * parmN is the name of the last (right-most) parameter specified in the function's prototype. * If parmN has the register storage class, proper operation of this function is not guaranteed. va_arg * In the va_arg macro, the argument ap must be the same as the va_list type object initialized with va_start (otherwise normal operation is not guaranteed). * va_arg returns a value in the relevant place of variable arguments as a type of type. The relevant place is the first variable argument immediately after va_start and each va_arg following that. * If the argument pointer ap is a null pointer, va_arg returns 0 (of type type). va_end * The va_end macro sets a null pointer in the argument pointer ap to inform the macro processor that all the parameters in the variable argument list have been processed.
User's Manual U14872EJ1V0UM
193
CHAPTER 10
LIBRARY FUNCTIONS
4-1
sprintf (normal model only)
I/O Functions
FUNCTION The sprintf function writes data into a character string (array) according to the format. HEADER stdio.h FUNCTION PROTOTYPE int sprintf(char *s,const char *format,...);
Function sprintf Arguments s ... Pointer to the string into which the output is to be written format ... Pointer to the string which indicates format commands ... ... Zero or more arguments to be converted Return Value Number of characters written in s (terminating null character is not counted.)
EXPLANATION * If there are fewer actual arguments than formats, operation is not guaranteed. If formats run out with actual arguments still remaining, the excess actual arguments are just evaluated and ignored. * sprintf converts zero or more arguments that follow format according to the format command specified by format and writes (copies) them into the string s. * Zero or more format commands may be used. Ordinary characters (other than format commands that begin with a % character) are output as is to the string s. Each format command takes zero or more arguments that follow format and outputs them to the string s. * Each format command begins with a % character and is followed by these: * Zero or more flags (to be explained later) that modify the meaning of the format command * Optional decimal integer which specify a minimum field width If the output width after the conversion is less than this minimum field width, this specifier pads the output with blanks of zeros on its left. (If the left-justifying flag "-" (minus) sign follows %, zeros are padded out to the right of the output.) The default padding is done with spaces. If the output is to be padded with 0s, place a 0 before the field width specifier. If the number or string is greater than the minimum field width, it will still be printed in full and not truncated.
194
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
sprintf (normal model only)
I/O Functions
* Optional precision (number of decimal places) specification (. integer) With d, i, o, u, x, and X type specifiers, the minimum number of digits is specified. With the s type specifier, the maximum number of characters (maximum field width) is specified. The number of digits to be output following the decimal point is specified for e, E, and f conversions. The number of maximum valid digits is specified for g and G conversions. This precision specification must be made in the form of (.integers). If the integer part is omitted, 0 is assumed to have been specified. The amount of padding resulting from this precision specification takes precedence over the padding by the field width specification. * Optional h, l and L modifiers The h modifier instructs the sprintf function to perform the d, i, o, u, x, or X type conversion that follows this modifier on short int or unsigned short int type. The h modifier instructs the sprintf function to perform the n type conversion that follows this modifier on a pointer to short int type. The l modifier instructs the sprintf function to perform the d, i, o, u, x, or X type conversion that follows this modifier on long int or unsigned long int type. The h modifier instructs the sprintf function to perform the n type conversion that follows this modifier on a pointer to long int type. For other type specifiers, the h, l or L modifier is ignored. * Character that specifies the conversion (to be explained later) In the minimum field width or precision (number of decimal places) specification, * may be used in place of an integer string. In this case, the integer value will be given by the int argument (before the argument to be converted). Any negative field width resulting from this will be interpreted as a positive field that follows the (minus) flag. All negative precision will be ignored. The following flags are used to modify a format command: - ................... The result of a conversion is left-justified within the field. +................... The result of a signed conversion always begins with a + or - sign. Space........... If the result of a signed conversion has no sign, a space is prefixed to the output. If the + (plus) flag and space flag are specified at the same time, the space flag will be ignored. # ................... The result is converted in the assignment form. In the o type conversion, precision is increased so that the first digit becomes 0. In the x or X type conversion, 0x or 0X is prefixed to a nonzero result. In the e, E, and f type conversions, a decimal point is forcibly inserted to all the output values (in the default without #, a decimal point is displayed only when there is a value to follow). In the g and G type conversions, a decimal point is forcibly inserted in all the output values, and truncation of 0 to follow will not be allowed (in the default without #, a decimal point is displayed only when there is a value to follow. The 0 to follow will be truncated). In all the other conversions, the # flag is ignored.
User's Manual U14872EJ1V0UM
195
CHAPTER 10
LIBRARY FUNCTIONS
sprintf (normal model only)
I/O Functions
The format codes for output conversion specifications are as follows, d ................... Converts int argument to signed decimal format. i .................... Converts int argument to signed decimal format. o ................... Converts int argument to unsigned octal format. u ................... Converts int argument to unsigned decimal format. x ................... Converts int argument to unsigned hexadecimal format (with lowercase letters abcdef). X................... Converts int argument to unsigned hexadecimal format (with uppercase letters ABCDEF). With d, i, o, u, x and X type specifiers, the minimum number of digits (minimum field width) of the result is specified. If the output is shorter than the minimum field width, it is padded with zeros. If no precision is specified, 1 is assumed to have been specified. Nothing will appear if 0 is converted with 0 precision. f .................... Converts double argument as a signed value with [-] dddd.dddd format. dddd is one or more decimal number(s). The number of digits before the decimal point is determined by the absolute value of the number, and the number of digits after the decimal point is determined by the required precision. When the precision is omitted, it is interpreted as 6. e ................... Converts double argument as a signed value with [-] d.dddd e [sign] ddd format. d is one decimal number, and dddd is one or more decimal number(s). ddd is exactly a three-digit decimal number, and the sign is + or -. When the precision is omitted, it is interpreted as 6 E................... The same format as that of e except E is added instead of e before the exponent. g ................... Uses whichever shorter method of f or e format when converting double argument based on the specified precision. e format is used only when the exponent of the value is smaller than - 4 or larger than the specified number by precision. The following 0s are truncated, and the decimal point is displayed only when one or more numbers follow. G .................. The same format as that of g except E is added instead of e before the exponent. c ................... Converts int argument to unsigned char and writes the result as a single character. s ................... The associated argument is a pointer to a string of characters and the characters in the string are written up to the terminating null character (but not included in the output). If precision is specified, the characters exceeding the maximum field width will be truncated off the end. When the precision is not specified or larger than the array, the array must include a null character. p ................... The associated argument is a pointer to void and the pointer value is displayed in hexadecimal 4 digits (with 0s prefixed to less than a 4-digit pointer value). The precision specification if any will be ignored. n ................... The associated argument is an integer pointer into which the number of characters written thus far in the string "s" is placed. No conversion is performed. % .................. Prints a % sign. The associated argument is not converted (but the flag and minimum field width specifications are valid).
196
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
sprintf (normal model only)
I/O Functions
* Operations for invalid conversion specifiers are not guaranteed. * When the actual argument is a union or a structure, or the pointer to indicate them (except the character type array in % s conversion or the pointer in % p conversion), operations are not guaranteed. * The conversion result will not be truncated even when there is no field width or the field width is small. In other words, when the number of characters of the conversion result are larger than the field width, the field is extended to the width that includes the conversion result. * The formats of the special output character string in %f, %e, %E, %g, %G conversions are shown below. non-numeric + - "(NaN)" "(+INF)" "(-INF)"
sprintf writes a null character at the end of the string s. (This character is included in the return value count.) The syntax of format commands is illustrated in Figure 10-2.
User's Manual U14872EJ1V0UM
197
CHAPTER 10
LIBRARY FUNCTIONS
sprintf (normal model only)
I/O Functions
Figure 10-2. Syntax of Format Commands
format:
Format command
Ordinary char.
Ordinary characters:
Characters except %
Format command:
%
Flags
Min. field width
Precision
h I L
Format code
Flags:
-
Format codes:
+
d i
Space
o u
#
x
X
Minimum field width:
Digits c * s
Precision:
.
p Digits n * f
e
E g G %
198
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
4-2
sscanf (normal model only)
I/O Functions
FUNCTION The sscanf function reads data from the input string (array) according to the format. HEADER stdio.h FUNCTION PROTOTYPE int sscanf(const char *s,const char *format,...);
Function sscanf Arguments s ... Pointer to the input string format ... Pointer to the string which indicates the input format commands ... ... Pointer to object in which converted values are to be stored, and zero or more arguments Return Value -1 if the string s is empty. Number of assigned input data items if the string s is not empty.
EXPLANATION * sscanf inputs data from the string pointed to by s. The string pointed to by format specifies the input string allowed for input. Zero or more arguments after format are used as pointers to an object. format specifies how data is to be converted from the input string. * If there are insufficient arguments to match the format commands pointed to by format, proper operation by the compiler is not guaranteed. For excessive arguments, expression evaluation will be performed but no data will be input. * The control string pointed to by format consists of zero or more format commands which are classified into the following three types. (a) White-space characters (one or more characters for which isspace becomes true) (b) Non-white-space characters (other than %) (c) Format specifiers * Each format specifier begins with the % character and is followed by these: * Optional * character which suppresses assignment of data to the corresponding argument * Optional decimal integer which specifies a maximum field width * Optional h, l or L modifier which indicates the object size on the receiving side If h precedes the d, i, o, or x format specifier, the argument is a pointer to not int but short int. If l precedes any of these format specifiers, the argument is a pointer to long int. Likewise, if h precedes the u format specifier, the argument is a pointer to unsigned short int. If l precedes the u format specifier, the argument is a pointer to unsigned long int. If l precedes the conversion specifier e, E, f, g, G, the argument is a pointer to double (a pointer to float in default without l). If L precedes, it is ignored. Remark Conversion specifier: Character to indicate the type of corresponding conversion (to be described later)
User's Manual U14872EJ1V0UM
199
CHAPTER 10
LIBRARY FUNCTIONS
sscanf (normal model only)
I/O Functions
sscanf executes the format commands in "format" in sequence and if any format command fails, the function will terminate. (a) A white-space character in the control string causes sscanf to read any number (including zero) of whitespace characters up to the first non-white-space character (which will not be read). This white-space character command fails if it does not encounter any non-white-space characters. (b) A non-white-space character causes sscanf to read and discard a matching character. This command fails if the specified character is not found. (c) The format commands define a collection of input streams for each type specifier (to be described later). The format commands are executed according to the following steps. * The input white-space characters (specified by isspace) are skipped over, except when the type specifier is [, c, or n. * The input data items are read from the string "s", except when the type specifier is n. The input data items are defined as the longest input stream of the first partial stream of the string indicated by the type specifier (but up to the maximum field width if so specified). The character next to the input data items is interpreted as not having been read. If the length of the input data items is 0, the format command execution fails. * The input data items (number of input characters with the type specifier n) are converted to the type specified by the type specifier except the type specifier %. If the input data items do not match the specified type, the command execution fails. Unless assignment is suppressed by *, the result of the conversion is stored in the object pointed to by the first argument which follows "format" and has not yet received the result of the conversion. The following type specifiers are available: d ........................... Converts a decimal integer (which may be signed). The corresponding argument must be a pointer to an integer. i ............................ Converts an integer (which may be signed). If a number is preceded by 0x or 0X, the number is interpreted as a hexadecimal integer. If a number is preceded by 0, the number is interpreted as an octal integer. Other numbers are regarded as decimal integers. The corresponding argument must be a pointer to an integer. o ........................... Converts an octal integer (which may be signed). The corresponding argument must be a pointer to an integer. u ........................... Converts an unsigned decimal integer. The corresponding argument must be a pointer to an unsigned integer. x ........................... Converts a hexadecimal integer (which may be signed). e, E, f, g, G........... Floating point value consists of optional sign (+ or -), one or more consecutive decimal number(s) including decimal point, optional exponent (e or E), and the following optional signed integer value. When overflow occurs as a result of conversion, or when underflow occurs with the conversion result , a non-normalized number or 0 becomes the conversion result. The corresponding argument is a pointer to float.
200
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
sscanf (normal model only)
I/O Functions
s ...........................
Input a character string consisting of a non-white-space character string.
The
corresponding argument is a pointer to an integer. 0x or 0X can be allocated at the first hexadecimal integer. The corresponding argument must be a pointer an array that has sufficient size to accommodate this character string and a null terminator. terminator will be automatically added. [............................ Inputs a character string consisting of expected character groups (called a scanset). The corresponding argument must be a pointer to the first character of an array that has sufficient size to accommodate this character string and a null terminator. terminator will be automatically added. The null The format commands continue from this The null
character up to the closing square bracket (]). The character string (called a scanlist) enclosed in the square brackets constitutes a scanset except when the character immediately after the opening square bracket is a circumflex (^). When the character is a circumflex, all the characters other than a scanlist between the circumflex and the closing square bracket constitute a scanset. and the next closing square list becomes the end of the scanlist. A hyphen (-) at other than the left or right end of a scanlist is interpreted as the punctuation mark for hyphenation if the character at the left of the range specifying hyphen (-) is not smaller than the right-hand character in ASCII code. c ........................... Inputs a character string consisting of the number of characters specified by the field width. (If the field width specification is omitted, 1 is assumed.) The corresponding argument must be a pointer to the first character of an array that has sufficient size to accommodate this character string. The null terminator will not be added. p........................... n........................... Reads an unsigned hexadecimal integer. pointer to void. Receives no input from the string s. The corresponding argument must be a pointer to an integer. The number of characters that are read thus far by this function from the string "s" is stored in the object that is pointed to by this pointer. command is not included in the return value assignment count. %.......................... Reads a % sign. Neither conversion nor assignment takes place. The %n format The corresponding argument must be a However, when a scanlist begins with [ ] or [^], this closing square bracket is contained in the scanlist
If a format specification is invalid, the format command execution fails. If a null terminator appears in the input stream, sscanf will terminate. If an overflow occurs in an integer conversion (with the d, i, o, u, x, or p format specifier), the higher bits will be truncated depending on the number of bits of the data type after the conversion. The syntax of input format commands is illustrated below.
User's Manual U14872EJ1V0UM
201
CHAPTER 10
LIBRARY FUNCTIONS
sscanf (normal model only)
I/O Functions
Figure 10-3. Syntax of Input Format Commands
White-space characters: Format:
Command
Space
Command:
White-space char.
\f
\n Ordinary char. Format specifier
\r
\t
Ordinary characters:
Characters except % and white space
\v
Format command:
%
*
Max. field width
h I
Format specifier
Max. field width: Format specifiers:
Digits L d i
scanlist:
^
Characters except
o
u
Characters except
x
s
scanlist
c
p
n
f
e
E
g
G %
202
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
4-3
printf (normal model only)
I/O Functions
FUNCTION printf outputs data to SFR according to the format. HEADER stdio.h FUNCTION PROTOTYPE int printf(const char *format, ...);
Function printf
Arguments format ...Pointer to the character string that indicates the output conversion specification ... ... 0 or more arguments to be converted
Return Value Number of character output to s (the null character at the end is not counted)
EXPLANATION * (0 or more) arguments following the format are converted and output using the putchar function, according to the output conversion specification specified in the format. * The output conversion specification is 0 or more directives. Normal characters (other than the conversion specification starting with %) are output as is using the putchar function. The conversion specification is output using the putchar function by fetching and converting the following (0 or more) arguments. * Each conversion specification is the same as that of the sprintf function.
User's Manual U14872EJ1V0UM
203
CHAPTER 10
LIBRARY FUNCTIONS
4-4
scanf (normal model only)
I/O Functions
FUNCTION scanf reads data from SFR according to the format. HEADER stdio.h FUNCTION PROTOTYPE int scanf(const char *format, ...);
Function scanf
Arguments format ... Pointer to the character string to indicate input conversion specification ... ... Pointer (0 or more) argument to the object to assign the converted value
Return Value When the character string s is not null ... Number of input items assigned
EXPLANATION * Performs input using the getchar function. conversion is performed by the input string. * When there are not enough arguments for format, normal operation is not guaranteed. When the number of arguments is excessive, the expression will be evaluated but not input. * format consists of 0 or more directives. The directives are as follows. (1) One or more null character (character that makes isspace true) (2) Normal character (other than %) (3) Conversion indication * If a conversion ends with an input character that conflicts with the input character, the conflicting input character is rounded down. The conversion indication is the same as that of the sscanf function. Specifies the input string permitted by the character string indicated by format. Uses the argument after format as the pointer to an object. format specifies how the
204
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
4-5
vprintf (normal model only)
I/O Functions
FUNCTION vprintf outputs data to SFR according to the format. HEADER stdio.h FUNCTION PROTOTYPE int vprintf(const char *format,va_list p);
Function vprintf
Arguments format ... Pointer to the character string that indicates output conversion specification p ... Pointer to the argument list
Return Value Number of output characters (the null character at the end is not counted)
EXPLANATION * The argument that the pointer of the argument list indicates is converted and output using the putchar function according to the output conversion specification specified by the format. * Each conversion specification is the same as that of the sprintf function.
User's Manual U14872EJ1V0UM
205
CHAPTER 10
LIBRARY FUNCTIONS
4-6
vsprintf (normal model only)
I/O Functions
FUNCTION vsprintf writes data to character strings according to the format. HEADER stdio.h FUNCTION PROTOTYPE int vsprintf(char *s,const char * format,va_list p);
Function vsprintf
Arguments s ... Pointer to the character string that writes the output format ... Pointer to the character string that indicates output conversion specification p ... Pointer to the argument list
Return Value Number of characters output to s (the null character at the end is not counted)
EXPLANATION * Writes out the argument that the pointer of argument list indicates to the character strings that s indicates according to the output conversion specification specified by format. * The output specification is the same as that of the sprintf function.
206
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
4-7
getchar
I/O Functions
FUNCTION getchar reads a character from SFR HEADER stdio.h FUNCTION PROTOTYPE int getchar(void);
Function getchar None
Arguments
Return Value A character read from SFR
EXPLANATION * Returns the value read from SFR symbol P0 (port 0). * Error check related to reading is not performed. * To change SFR to read, it is necessary either that the source be changed to be re-registered to the library or that the user create a new getchar function.
User's Manual U14872EJ1V0UM
207
CHAPTER 10
LIBRARY FUNCTIONS
4-8
gets
I/O Functions
FUNCTION gets reads a character string. HEADER stdio.h FUNCTION PROTOTYPE char *gets(char *s);
Function gets
Arguments s ... Pointer to input character string
Return Value Normal ... s If the end of the file is detected without reading a character ... Null pointer
EXPLANATION * Reads a character string using the getchar function and stores in the array that s indicates. * When the end of the file is detected (getchar function returns -1) or when a line feed character is read, the reading of a character string ends. The line feed character read is abandoned, and a null character is written at the end of the last character stored in the array. * When the return value is normal, it returns s. * When the end of the file is detected and no character is read in the array, the contents of the array remain unchanged, and a null pointer is returned.
208
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
4-9
putchar
I/O Functions
FUNCTION putchar outputs a character to SFR. HEADER stdio.h FUNCTION PROTOTYPE int putchar(int c);
Function putchar
Arguments c ... Character to be output
Return Value Character output
EXPLANATION * Writes the character specified by c to the SFR symbol P0 (port 0) (converted to unsigned char type). * Error check related to writing is not performed. * To change SFR to write, it is necessary either that the source is changed and re-registered to the library or that the user create a new putchar function.
User's Manual U14872EJ1V0UM
209
CHAPTER 10
LIBRARY FUNCTIONS
4-10 puts
I/O Functions
FUNCTION puts outputs a character string. HEADER stdio.h FUNCTION PROTOTYPE int puts(const char *s);
Function puts
Arguments s ...Pointer to an output character string
Return Value Normal ... 0 When putchar function returns -1 ... -1
EXPLANATION * Writes the character string indicated by s using the putchar function, a line feed character is added at the end of the output. * Writing of the null character at the end of the character string is not performed. * When the return value is normal, 0 is returned, and when the putchar function returns -1, -1 is returned.
210
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
5-1
atoi atol
Utility Functions
FUNCTION The string function atoi converts the contents of a decimal integer string to an int value. The string function atol converts the contents of a decimal integer string to a long int value. HEADER stdlib.h FUNCTION PROTOTYPE int atoi(const char *nptr); long int atol(const char *nptr);
Function atoi
Arguments nptr... String to be converted
Return Value * int value if converted properly * INT_MAX (32767) if positive overflow occurs * INT_MIN (-32768) if negative overflow occurs * 0 if the string is invalid
atol
* long int value if converted properly; * LONG_MAX (2147483647) for positive overflow; * LONG_MIN (-2147483648) for negative overflow; * 0 if the string is invalid
User's Manual U14872EJ1V0UM
211
CHAPTER 10
LIBRARY FUNCTIONS
atoi atol
Utility Functions
EXPLANATION atoi * The atoi function converts the first part of the string pointed to by pointer nptr to an int value. * The atoi function skips over zero or more white-space characters (for which isspace becomes true) from the beginning of the string and converts the string from the character next to the skipped white-spaces to an integer (until other than digits or a null character appears in the string). If no digits to convert are found in the string, the function returns 0. If an overflow occurs, the function returns INT_MAX (32767) for a positive overflow and INT_MIN (-32768) for a negative overflow. atol * The atol function converts the first part of the string pointed to by pointer nptr to a long int value. * The atol function skips over zero or more white-space characters (for which isspace becomes true) from the beginning of the string and converts the string from the character next to the skipped white-spaces to an integer (until other than digits or a null character appears in the string). If no digits to convert are found in the string, the function returns 0. If an overflow occurs, the function returns LONG_MAX (2147483647) for a positive overflow and LONG_MIN (-2147483648) for a negative overflow.
212
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
5-2
strtol strtoul
Utility Functions
FUNCTION The string function strtol converts a string to a long integer. The string function strtoul converts a string to an unsigned long integer. HEADER stdlib.h FUNCTION PROTOTYPE long int strtol(const char *nptr,char **endptr,int base); unsigned long int strtoul(const char *nptr,char **endptr,int base);
Function strtol
Arguments nptr... String to be converted endptr ... Pointer storing pointer to unrecognizable section base ... Specified base number
Return Value * long int value if converted properly * LONG_MAX (2147483647) for positive overflow * LONG_MIN (-2147483648) for negative overflow * 0 if not converted
strtoul
* unsigned long if converted properly * ULONG_MAX (4294967295U) if overflow occurs * 0 if not converted
User's Manual U14872EJ1V0UM
213
CHAPTER 10
LIBRARY FUNCTIONS
strtol strtoul
Utility Functions
EXPLANATION strtol * The strtol function disassembles the string pointed by pointer nptr into the following three parts. (1) String of white-space characters that may be empty (to be specified by isspace) (2) Integer representation by the base determined by the value of base (3) String of one or more characters that cannot be recognized (including null terminators) The strtol function converts part (2) of the string into an integer and returns this integer value. * A base of 0 indicates that the base should be determined from the leading digits of the string. A leading 0x or 0X indicates a hexadecimal number; a leading 0 indicates an octal number; otherwise, the number is interpreted as decimal. (In this case, the number may be signed). * If the base is 2 to 36, the set of letters from a to z or A to Z which can be part of a number (and which may be signed) with any of these bases are taken to represent 10 to 35. A leading 0x or 0X is ignored if the base is 16. * If endptr is not a null pointer, a pointer to the part (3) of the string is stored in the object pointed to by endptr. * If the correct value causes an overflow, the function returns LONG_MAX (2147483647) for a positive overflow or LONG_MIN (-2147483648) for a negative overflow depending on the sign and sets errno to ERANGE (2). * If the string (2) is empty or the first non-white-space character of the string (2) is not appropriate for an integer with the given base, the function performs no conversion and returns 0. In this case, the value of the string nptr is stored in the object pointed to by endptr (if it is not a null string). This holds true with the bases 0 and 2 to 36. strtoul * The strtoul function disassembles the string pointed by pointer nptr into the following three parts. (1) String of white-space characters that may be empty (to be specified by isspace) (2) Integer representation by the base determined by the value of base (3) String of one or more characters that cannot be recognized (including null terminators) The strtoul function converts part (2) of the string into a unsigned integer and returns this unsigned integer value. * A base of 0 indicates that the base should be determined from the leading digits of the string. A leading 0x or 0X indicates a hexadecimal number; a leading 0 indicates an octal number; otherwise, the number is interpreted as decimal. * If the base is 2 to 36, the set of letters from a to z or A to Z which can be part of a number (and which may be signed) with any of these bases are taken to represent 10 to 35. A leading 0x or 0X is ignored if the base is 16. * If endptr is not a null pointer, a pointer to the part (3) of the string is stored in the object pointed to by endptr.
214
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
strtol strtoul
Utility Functions
* If the correct value causes an overflow, the function returns ULONG_MAX (4294967295U) and sets errno to ERANGE (2). * If the string (2) is empty or the first non-white-space character of the string (2) is not appropriate for an integer with the given base, the function performs no conversion and returns 0. In this case, the value of the string nptr is stored in the object pointed to by endptr (if it is not a null string). This holds true with the bases 0 and 2 to 36.
User's Manual U14872EJ1V0UM
215
CHAPTER 10
LIBRARY FUNCTIONS
5-3
calloc
Utility Functions
FUNCTION The memory function calloc allocates an array area and then initializes the area to 0. HEADER stdlib.h FUNCTION PROTOTYPE void *calloc(size_t nmemb,size_t size);
Function calloc
Arguments nmemb ... Number of members in the array size ... Size of each member
Return Value * Pointer to the beginning of the allocated area if the requested size is allocated * Null pointer if the requested size is not allocated
EXPLANATION * The calloc function allocates an area for an array consisting of n number of members (specified by nmemb), each of which has the number of bytes specified by size and initializes the area (array members) to zero. * Returns the pointer to the beginning of the allocated area if the requested size is allocated. * Returns the null pointer if the requested size is not allocated. * The memory allocation will start from a break value and the address next to the allocated space will become a new break value. See 5-11 brk for break value setting with the memory function brk.
216
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
5-4
free
Utility Functions
FUNCTION The memory function free releases the allocated block of memory. HEADER stdlib.h FUNCTION PROTOTYPE void free(void *ptr);
Function free
Arguments ptr ... Pointer to the beginning of block to be released None
Return Value
EXPLANATION * The free function releases the allocated space (before a break value) pointed to by ptr. (malloc, calloc, or realloc called after free will allocate space from ptr.) * If ptr does not point to the allocated space, the free will take no action. (Freeing the allocated space is performed by setting ptr as a new break value.)
User's Manual U14872EJ1V0UM
217
CHAPTER 10
LIBRARY FUNCTIONS
5-5
malloc
Utility Functions
FUNCTION The memory function malloc allocates a block of memory. HEADER stdlib.h FUNCTION PROTOTYPE void *malloc(size_t size);
Function malloc
Arguments size ... Size of memory block to be allocated
Return Value * Pointer to the beginning of the allocated area if the requested size is allocated * Null pointer if the requested size is not allocated
EXPLANATION * The malloc function allocates a block of memory for the number of bytes specified by size and returns a pointer to the first byte of the allocated area. * If memory cannot be allocated, the function returns a null pointer. * This memory allocation will start from a break value and the address next to the allocated area will become a new break value. See 5-11 brk for break value setting with the memory function brk.
218
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
5-6
realloc
Utility Functions
FUNCTION The memory function realloc reallocates a block of memory (namely, changes the size of the allocated memory). HEADER stdlib.h FUNCTION PROTOTYPE void *realloc(void *ptr,size_t size);
Function realloc
Arguments ptr ... Pointer to the beginning of block previously allocated size ... New size to be given to this block
Return Value * Pointer to the beginning of the reallocated space if the requested size is reallocated * Pointer to the beginning of the allocated space if ptr is a null pointer * Null pointer if the requested size is not reallocated or "ptr" is not a null pointer
EXPLANATION * The realloc function changes the size of the allocated space (before a break value) pointed to by ptr to that specified by size. If the value of size is greater than the size of the allocated space, the contents of the allocated space up to the original size will remain unchanged. The realloc function allocates only for the increased space. If the value of size is less than the size of the allocated space, the function will free the reduced space of the allocated space. * If ptr is a null pointer, the realloc function will newly allocate a block of memory of the specified size (same as malloc). * If ptr does not point to the block of memory previously allocated or if no memory can be allocated, the function executes nothing and returns a null pointer. * Reallocation will be performed by setting the address of ptr plus the number of bytes specified by size as a new break value.
User's Manual U14872EJ1V0UM
219
CHAPTER 10
LIBRARY FUNCTIONS
5-7
abort
Utility Functions
FUNCTION The program control function abort causes immediate, abnormal termination of a program. HEADER stdlib.h FUNCTION PROTOTYPE void abort(void);
Function abort None
Arguments
Return Value No return
EXPLANATION * The abort function loops and can never return to its caller. * The user must create the abort processing routine.
220
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
5-8
atexit exit
Utility Functions
FUNCTION atexit registers the function called at the normal termination. exit terminates a program. HEADER stdlib.h FUNCTION PROTOTYPE int atexit(void(*func)(void)); void exit(int status);
Function atexit
Arguments func ... Pointer to function to be registered
Return Value * 0 if function is registered as wrap-up function * 1 if function cannot be registered No return.
exit
status ... Status value indicating termination
EXPLANATION atexit * The atexit function registers the wrap-up function pointed to by func so that it is called without argument upon normal program termination by calling exit or returning from main. * Up to 32 wrap-up functions may be established. If the wrap-up function can be registered, atexit returns 0. If no more wrap-up functions can be registered because 32 wrap-up functions have already been registered, the function returns 1. exit * The exit function causes immediate, normal termination of a program. * This function calls the wrap-up functions in the reverse of the order in which they were registered with atexit. * The exit function loops and can never return to its caller. * The user must create the exit processing routine.
User's Manual U14872EJ1V0UM
221
CHAPTER 10
LIBRARY FUNCTIONS
5-9
abs labs
Utility Functions
FUNCTION The mathematical function abs returns the absolute value of its int type argument. The mathematical function labs returns the absolute value of its long type argument. HEADER stdlib.h FUNCTION PROTOTYPE int abs(int j); long int labs(long int j);
Function abs
Arguments j ... Absolute value to be obtained
Return Value * Absolute value of j if j falls within: -32767 j 32767 * -32768 (0x8000) if j is -32768
labs
* Absolute value of j if j falls within -2147483647 j 2147483647 * -2147483648 (0x80000000) if the value of j is -2147483648
EXPLANATION abs * The abs returns the absolute value of its int type argument. * If j is -32768, the function returns -32768. labs * The labs returns the absolute value of its long type argument. * If the value of j is -2147483648, the function returns -2147483648.
222
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
5-10 div (normal model only) ldiv (normal model only)
Utility Functions
FUNCTION The mathematical function div performs the integer division of numerator divided by denominator. The mathematical function ldiv performs the long integer division of numerator divided by denominator. HEADER stdlib.h FUNCTION PROTOTYPE div_t div(int numer,int denom); ldiv_t ldiv(long int numer,long int denom);
Function div
Arguments numer ... Numerator of the division denom ... Denominator of the
Return Value Quotient to the quot element and the remainder to the rem element of div_t type member Quotient to the quot element and the remainder to the rem element of ldiv_t type member
ldiv
division
EXPLANATION div * The div function performs the integer division of numerator divided by denominator. * The absolute value of the quotient is defined as the largest integer not greater than the absolute value of numer divided by the absolute value of denom. The remainder always has the same sign as the result of the division (plus if numer and denom have the same sign; otherwise minus). * The remainder is the value of numer - denom*quotient. * If denom is 0, the quotient becomes 0 and the remainder becomes numer. * If numer is -32768 and denom is -1, the quotient becomes -32768 and the remainder becomes 0. ldiv * The ldiv function performs the long integer division of numerator divided by denominator. * The absolute value of the quotient is defined as the largest long int type integer not greater than the absolute value of numer divided by the absolute value of denom. The remainder always has the same sign as the result of the division (plus if numer and denom have the same sign; otherwise minus). * The remainder is the value of numer - denom*quotient. * If denom is 0, the quotient becomes 0 and the remainder becomes numer. * If numer is -2147483648 and denom is -1, the quotient becomes -2147483648 and the remainder becomes 0.
User's Manual U14872EJ1V0UM
223
CHAPTER 10
LIBRARY FUNCTIONS
5-11 brk sbrk
Utility Functions
FUNCTION The memory function brk sets a break value. The memory function sbrk increments or decrements the set break value. HEADER stdlib.h FUNCTION PROTOTYPE int brk(char *endds); char *sbrk(int incr);
Function brk
Arguments endds ... Break value to be set block to be released
Return Value * 0 if break value is set properly * -1 if break value cannot be changed * Old break value if incremented or decremented properly * -1 if old break value cannot be incremented or decremented
sbrk
incr ... Value (bytes) by which set break value is to be incremented/decremented.
EXPLANATION brk * The brk function sets the value given by endds as a break value (the address next to the end address of an allocated block of memory). * If endds is outside the permissible address range, the function sets no break value and sets errno to ENOMEM (3). sbrk * The sbrk function increments or decrements the set break value by the number of bytes specified by incr. (Increment or decrement is determined by the plus or minus sign of incr.) * If the incremented or decremented break value is outside the permissible address range, the function does not change the original break value and sets errno to ENOMEM (3).
224
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
5-12 atof strtod
Utility Functions
FUNCTION The string function atof converts the contents of a decimal integer string to a double value. The string function strtod converts the contents of a string to a double value. HEADER stdlib.h FUNCTION PROTOTYPE double atof(const char *nptr); double strtod(const char *nptr, char **endptr);
Function atof
Arguments nptr ... String to be converted
Return Value * Converted value if converted properly * HUGE_VAL (with sign of overflowed value) if positive overflow occurs * 0 if negative overflow occurs * 0 if the string is invalid
strtod
nptr ... String to be converted endptr ... Pointer storing pointer to unrecognizable block
* Converted value if converted properly * HUGE_VAL (with sign of overflowed value) if positive overflow occurs * 0 if negative overflow occurs * 0 if the string is invalid
User's Manual U14872EJ1V0UM
225
CHAPTER 10
LIBRARY FUNCTIONS
atof strtod
Utility Functions
EXPLANATION atof * The atof function converts the string pointed to by pointer nptr to a double value. * The atof function skips over zero or more white-space characters (for which isspace becomes true) from the beginning of the string and converts the string from the character next to the skipped white-spaces to a floating-point number (until other than digits or a null character appears in the string). * A floating-point number is returned when converted properly. * If an overflow occurs on conversion, HUGE_VAL with the sign of the overflowed value is returned and ERANGE is set to errno. * If valid digits are deleted due to an underflow or an overflow, a non-normalized number and 0 are returned respectively, and ERANGE is set to errno. * IF conversion cannot be performed, 0 is returned. strtod * The strtod function converts the string pointed to by pointer nptr to a double value. * The strtod function skips over zero or more white-space characters (for which isspace becomes true) from the beginning of the string and converts the string from the character next to the skipped white-spaces to a floating-point number (until other than digits or a null character appears in the string). * A floating-point number is returned when converted properly. * If an overflow occurs on conversion, HUGE_VAL with the sign of the overflowed value is returned and ERANGE is set to errno. * If valid digits are deleted due to an underflow or an overflow, a non-normalized number and 0 are returned respectively, and ERANGE is set to errno. In addition, endptr stores a pointer for next character string at that time. * IF conversion cannot be performed, 0 is returned.
226
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
5-13 itoa ltoa (normal model only) ultoa (normal model only)
FUNCTION The string function itoa converts an int integer to its string equivalent. The string function ltoa converts a long int integer to its string equivalent. The string function ultoa converts an unsigned long integer to its string equivalent. HEADER stdlib.h FUNCTION PROTOTYPE char *itoa(int value,char *string,int radix); char *ltoa(long value,char *string,int radix); char *ultoa(unsigned long value,char *string,int radix);
Utility Functions
Function itoa, ltoa, ultoa
Arguments value ... String to which integer is to be converted string ... Pointer to the conversion result radix ... Base of output string
Return Value * Pointer to the converted string if converted properly * Null pointer if not converted properly
EXPLANATION itoa, ltoa, ultoa * The itoa, ltoa, and ultoa functions all convert the integer value specified by value to its string equivalent which is terminated with a null character and store the result in the area pointed to by "string". * The base of the output string is determined by radix, which must be in the range 2 through 36. Each function performs conversion based on the specified radix and returns a pointer to the converted string. pointer. If the specified radix is outside the range 2 through 36, the function performs no conversion and returns a null
User's Manual U14872EJ1V0UM
227
CHAPTER 10
LIBRARY FUNCTIONS
5-14 rand srand
Utility Functions
FUNCTION The mathematical function rand generates a sequence of psuedo-random numbers. The mathematical function srand sets a starting value (seed) for the sequence generated by rand. HEADER stdlib.h FUNCTION PROTOTYPE int rand(void); void srand(unsigned int seed);
Function rand None
Arguments
Return Value Psuedo-random integer in the range of 0 to RAND_MAX None
srand
seed ... Starting value for psuedo-random number generator
EXPLANATION rand * Each time the rand function is called, it returns a psuedo-random integer in the range of 0 to RAND_MAX. srand * The srand function sets a starting value for a sequence of random numbers. seed is used to set a starting point for a progression of random numbers that is a return value when rand is called. If the same seed value is used, the sequence of psuedo-random numbers is the same when srand is called again. * Calling rand before srand is used to set a seed is the same as calling rand after srand has been called with seed = 1. (The default seed is 1.)
228
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
5-15 bsearch (normal model only)
Utility Functions
FUNCTION The bsearch function performs a binary search. HEADER stdlib.h FUNCTION PROTOTYPE void *bsearch(const void *key,const void *base,size_t nmemb, size_t size,int (*compare)(const void *,const void *));
Function bsearch
Arguments key ... Pointer to key for which search is made base ... Pointer to sorted array which contains information to search nmemb ... Number of array elements size ... Size of an array compare ... Pointer to function used to compare two keys
Return Value * Pointer to the first member that matches "key" if the array contains the key; * Null pointer if the key is not contained in the array
EXPLANATION * The bsearch function performs a binary search on the sorted array pointed to by base and returns a pointer to the first member that matches the key pointed to by key. The array pointed to by base must be an array which consists of nmemb number of members each of which has the size specified by size and must have been sorted in ascending order. * The function pointed to by compare takes two arguments (key as the 1st argument and array element as the 2nd argument), compares the two arguments, and returns: - Negative value if the 1st argument is less than the 2nd argument - 0 if both arguments are equal - Positive integer if the 1st argument is greater than the 2nd argument * When the -ZR option is specified, the function passed to the argument of the bsearch function must be a pascal function.
User's Manual U14872EJ1V0UM
229
CHAPTER 10
LIBRARY FUNCTIONS
5-16 qsort (normal model only)
Utility Functions
FUNCTION The qsort function sorts the members of a specified array using a quicksort algorithm. HEADER stdlib.h FUNCTION PROTOTYPE void qsort(void *base,size_t nmemb,size_t size, int (*compare)(const void *,const void *));
Function qsort
Arguments base ... Pointer to array to be sorted nmemb ... Number of members in the array size ... Size of an array member compare ... Pointer to function used to compare two keys None
Return Value
EXPLANATION * The qsort function sorts the members of the array pointed to by base in ascending order. The array pointed to by base consists of nmemb number of members each of that has the size specified by size. * The function pointed to by compare takes two arguments (array elements 1 and 2), compares the two arguments, and returns: * The array element 1 as the 1st argument and array element 2 as the 2nd argument Negative value if the 1st argument is less than the 2nd argument 0 if both arguments are equal Positive integer if the 1st argument is greater than the 2nd argument * If the two array elements are equal, the element nearest to the top of the array will be sorted first. * When the -ZR option is specified, the function passed to the argument of the qsort function must be a pascal function.
230
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
5-17 strbrk
Utility Functions
FUNCTION strbrk sets a break value. HEADER stdlib.h FUNCTION PROTOTYPE int strbrk(char *endds);
Function strbrk
Arguments ends ... Break value to set
Return Value Normal ... 0 When a break value cannot be changed ... -1
EXPLANATION * Sets the value given by endds to the break value (the address following the address at the end of the area to be allocated). * When endds is out of the permissible range, the break value is not changed. ENOMEM(3) is set to errno and -1 is returned.
User's Manual U14872EJ1V0UM
231
CHAPTER 10
LIBRARY FUNCTIONS
5-18 strsbrk
Utility Functions
FUNCTION strsbrk increases/decreases a break value. HEADER stdlib.h FUNCTION PROTOTYPE char *strsbrk(int incr);
Function strsbrk
Arguments incr ... Amount to increase/decrease a break value
Return Value Normal ... Old break value When a break value cannot be increased/decreased ... -1
EXPLANATION * incr byte increases/decreases a break value (depending on the sign of incr). * When the break value is out of the permissible range after increasing/decreasing, a break value is not changed. ENOMEM(3) is set to errno, and -1 is returned.
232
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
5-19 stritoa strltoa (normal model only) strultoa (normal model only)
FUNCTION stritoa converts int to a character string. strltoa converts long to a character string. strultoa converts unsigned long to a character string. HEADER stdlib.h FUNCTION PROTOTYPE char *stritoa(int value,char *string,int radix); char *strltoa(long value,char *string,int radix); char *strultoa(unsigned long value,char *string,int radix);
Utility Functions
Function stritoa strltoa strultoa
Arguments value ... Character string to convert string ... Pointer to conversion result radix ... Radix to specify
Return Value Normal ... Pointer to the converted character string Other ... Null pointer
EXPLANATION stritoa, strltoa, strultoa * Converts the specified numeric value value to a character string that ends with a null character, and stores the result in the area specified by string. The conversion is performed using the specified radix, and the pointer to the converted character string will be returned. * radix must be a value in the range of 2 to 36. In other cases, the conversion is not performed and a null pointer is returned.
User's Manual U14872EJ1V0UM
233
CHAPTER 10
LIBRARY FUNCTIONS
6-1
memcpy memmove
Character String/Memory Functions
FUNCTION The memory function memcpy copies a specified number of characters from a source area of memory to a destination area of memory. The memory function memmove is identical to memcpy, except that it allows overlap between the source and destination areas. HEADER string.h FUNCTION PROTOTYPE void *memcpy (void *s1, const void *s2, size_t n); void *memmove (void *s1, const void *s2, size_t n);
Function memcpy, memmove
Arguments s1 ... Pointer to object into which data is to be copied s2 ... Pointer to object containing data to be copied n ... Number of characters to be copied
Return Value Value of s1
EXPLANATION memcpy * The memcpy function copies n number of consecutive bytes from the object pointed to by s2 to the object pointed to by s1. * If s2234
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
6-2
strcpy strncpy
Character String/Memory Functions
FUNCTION The string function strcpy is used to copy the contents of one character string to another. The string function strncpy is used to copy up to a specified number of characters from one character string to another. HEADER string.h FUNCTION PROTOTYPE char *strcpy (char *s1, const char *s2); char *strncpy (char *s1, const char *s2, size_t n);
Function strcpy, strncpy
Arguments s1... Pointer to copy destination array s2 ... Pointer to copy source array n ... Number of characters to be copied
Return Value Value of s1
EXPLANATION strcpy * The strcpy function copies the contents of the character string pointed to by s2 to the array pointed to by s1 (including the terminating character). * If s2 < s1 (s2 + Character length to be copied), the behavior of strcpy is not guaranteed (as copying starts in sequence from the beginning, not from the specified string). strncpy * The strncpy function copies up to the characters specified by n from the string pointed to by s2 to the array pointed to by s1. * If s2 < s1 (s2 + Character length to be copied or minimum value of s2 + n - 1), the behavior of strncpy is not guaranteed (as copying starts in sequence from the beginning, not from the specified string). * If the string pointed by s2 is less than the characters specified by n, nulls will be appended to the end of s1 until n characters have been copied. If the string pointed to by s2 is longer than n characters, the resultant string that is pointed to by s1 will not be null terminated.
User's Manual U14872EJ1V0UM
235
CHAPTER 10
LIBRARY FUNCTIONS
6-3
strcat strncat
Character String/Memory Functions
FUNCTION The string function strcat concatenates one character string to another. The string function strncat concatenates up to a specified number of characters from one character string to another. HEADER string.h FUNCTION PROTOTYPE char *strcat (char *s1, const char *s2); char *strncat (char *s1, const char *s2, size_t n);
Function strcat, strncat
Arguments s1... Pointer to a string to which a copy of another string (s2) is to be concatenated s2 ... Pointer to a string, copy of which is to be concatenated to another string (s1). n ... Number of characters to be concatenated
Return Value Value of s1
EXPLANATION strcat * The strcat function concatenates a copy of the string pointed to by s2 (including the null terminator) to the string pointed to by s1. The null terminator originally ending s1 is overwritten by the first character of s2. * When copying is performed between objects overlapping each other, the operation is not guaranteed. strncat * The strncat function concatenates not more than the characters specified by n of the string pointed to by s2 (excluding the null terminator) to the string pointed to by s1. The null terminator originally ending s1 is overwritten by the first character of s2. * If the string pointed to by s2 has fewer characters than specified by n, the strncat function concatenates the string including the null terminator. If there are more characters than specified by n, the n character section is concatenated starting from the top. * The null terminator must always be concatenated. * When copying is performed between objects overlapping each other, the operation is not guaranteed.
236
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
6-4
memcmp
Character String/Memory Functions
FUNCTION The memory function memcmp compares two data objects, with respect to a given number of characters. HEADER string.h FUNCTION PROTOTYPE int memcmp (const void *s1, const void *s2, size_t n);
Function memcmp
Arguments s1, s2 ... Pointers to two data objects to be compared n ... Number of characters to compare
Return Value * 0 if s1 and s2 are equal * Positive value if s1 is greater than s2; negative value if s1 is less than s2 (s1 - s2)
EXPLANATION * The memcmp function compares the data object pointed to by s1 with the data object pointed to by s2 with respect to the number of bytes specified by n. * If the two objects are equal, the function returns 0. * The function returns a positive value if the object s1 is greater than the object s2 and a negative value if s1 is less than s2.
User's Manual U14872EJ1V0UM
237
CHAPTER 10
LIBRARY FUNCTIONS
6-5
strcmp strncmp
Character String/Memory Functions
FUNCTION The string function strcmp compares two character strings. The string function strncmp compares not more than a specified number of characters from two character strings. HEADER string.h FUNCTION PROTOTYPE char *strcmp (char *s1, const char *s2); char *strncmp (char *s1, const char *s2, size_t n);
Function strcmp
Arguments s1... Pointer to one string to be compared s2 ... Pointer to the other string to be compared
Return Value * 0 if s1 is equal to s2 * Integer less than 0 or greater than 0 if s1 is less than or greater than s2 (s1 - s2) * 0 if s1 is equal to s2 within characters specified by n * Integer less than 0 or greater than 0 if s1 is less than or greater than s2 (s1 - s2) within characters specified by n
strncmp
s1... Pointer to one string to be compared s2 ... Pointer to the other string to be compared n ... Number of characters to be compared
EXPLANATION strcmp * The strcmp function compares the two null terminated strings pointed to by s1 and s2, respectively. * If s1 is equal to s2, the function returns 0. If s1 is less than or grater than s2, the function returns an integer less than 0 (a negative number) or greater than 0 (a positive number) (s1 - s2). strncmp * The strncmp function compares not more than the characters specified by n from the two null terminated strings pointed to by s1 and s2, respectively. * If s1 is equal to s2 within the specified characters, the function returns 0. If s1 is less than or greater than s2 within the specified characters, the function returns an integer less than 0 (a negative number) or greater than 0 (a positive number) (s1 - s2).
238
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
6-6
memchr
Character String/Memory Functions
FUNCTION The memory function memchr converts a specified character to unsigned char, searches for it, and returns a pointer to the first occurrence of this character in an object of a given size. HEADER string.h FUNCTION PROTOTYPE void *memchr (const void *s, int c, size_t
n);
Function memchr
Arguments s ... Pointer to objects in memory subject to search c ... Character to be searched n ... Number of bytes to be searched
Return Value * Pointer to the first occurrence of c if c is found * Null pointer if c is not found
EXPLANATION * The memchr function first converts the character specified by c to unsigned char and then returns a pointer to the first occurrence of this character within the n number of bytes from the beginning of the object pointed to by s. * If the character is not found, the function returns a null pointer.
User's Manual U14872EJ1V0UM
239
CHAPTER 10
LIBRARY FUNCTIONS
6-7
strchr strrchr
Character String/Memory Functions
FUNCTION The string function strchr returns a pointer to the first occurrence of a specified character in a string. The string function strrchr returns a pointer to the last occurrence of a specified character in a string. HEADER string.h FUNCTION PROTOTYPE char *strchr (const char *s, int c); char *strrchr (const char *s, int c);
Function strchr, strrchr
Arguments s... Pointer to string to be searched c ... Character specified for search
Return Value * Pointer indicating the first or last occurrence of c in string s if c is found in s * Null pointer if c is not found in s
EXPLANATION strchr * The strchr function searches the string pointed to by s for the character specified by c and returns a pointer to the first occurrence of c (converted to char type) in the string. * The null terminator is regarded as part of the string. * If the specified character is not found in the string, the function returns a null pointer. strrchr * The strrchr function searches the string pointed to by s for the character specified by c and returns a pointer to the last occurrence of c (converted to char type) in the string. * The null terminator is regarded as part of the string. * If no match is found, the function returns a null pointer.
240
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
6-8
strspn strcspn
Character String/Memory Functions
FUNCTION The string function strspn returns the length of the initial substring of a string that is made up of only those characters contained in another string. The string function strcspn returns the length of the initial substring of a string that is made up of only those characters not contained in another string. HEADER string.h FUNCTION PROTOTYPE size_t strspn (const char *s1, const char *s2); size_t strcspn (const char *s1, const char *2);
Function strspn
Arguments s1... Pointer to string to be searched s2 ... Pointer to string whose characters are specified for match
Return Value Length of substring of the string s1 that is made up of only those characters contained in the string s2 Length of substring of the string s1 that is made up of only those characters not contained in the s2
strcspn
EXPLANATION strspn * The strspn function returns the length of the substring of the string pointed to by s1 that is made up of only those characters contained in the string pointed to by s2. In other words, this function returns the index of the first character in the string s1 that does not match any of the characters in the string s2. * The null terminator of s2 is not regarded as part of s2. strcspn * The strcspn function returns the length of the substring of the string pointed to by s1 that is made up of only those characters not contained in the string pointed to by s2. In other words, this function returns the index of the first character in the string s1 that matches any of the characters in the string s2. * The null terminator of s2 is not regarded as part of s2.
User's Manual U14872EJ1V0UM
241
CHAPTER 10
LIBRARY FUNCTIONS
6-9
strpbrk
Character String/Memory Functions
FUNCTION The string function strpbrk returns a pointer to the first character in a string to be searched that matches any character in a specified string. HEADER string.h FUNCTION PROTOTYPE char *strpbrk (const char *s1, const char *s2);
Function strpbrk
Arguments s1... Pointer to string to be searched s2 ... Pointer to string whose characters are specified for match
Return Value * Pointer to the first character in the string s1 that matches any character in the string s2 if any match is found * Null pointer if no match is found
EXPLANATION * The strpbrk function returns a pointer to the first character in the string pointed to by s1 that matches any character in the string pointed to by s2. * If none of the characters in the string s2 is found in the string s1, the function returns a null pointer.
242
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
6-10 strstr
Character String/Memory Functions
FUNCTION The string function strstr returns a pointer to the first occurrence in the string to be searched of a specified string. HEADER string.h FUNCTION PROTOTYPE char *strstr (const char *s1, const char *s2);
Function strstr
Arguments s1... Pointer to string to be searched s2 ... Pointer to specified string
Return Value * Pointer to the first appearance in the string s1 of the string s2 if s2 is found in s1 * Null pointer if s2 is not found in s1 * Value of s1 if s2 is a null string
EXPLANATION * The strstr function returns a pointer to the first appearance in the string pointed to by s1 of the string pointed to by s2 (except the null terminator of s2). * If the string s2 is not found in the string s1, the function returns a null pointer. * If the string s2 is a null string, the function returns the value of s1.
User's Manual U14872EJ1V0UM
243
CHAPTER 10
LIBRARY FUNCTIONS
6-11 strtok
Character String/Memory Functions
FUNCTION The string function strtok returns a pointer to a token taken from a string (by disassembling it into a string consisting of characters other than delimiters). HEADER string.h FUNCTION PROTOTYPE char *strtok (char *s1, const char *s2);
Function strtok
Arguments s1... Pointer to string from which tokens are to be obtained or null pointer s2 ... Pointer to string containing delimiters of token
Return Value * Pointer to the first character of a token if it is found * Null pointer if there is no token to return
EXPLANATION * A token is a string consisting of characters other than delimiters in the string to be specified. * If s1 is a null pointer, the string pointed to by the saved pointer in the previous strtok call will be disassembled. However, if the saved pointer is a null pointer, the function returns a null pointer without doing anything. * If s1 is not a null pointer, the string pointed to by s1 will be disassembled. * The strtok function searches the string pointed to by s1 for any character not contained in the string pointed to by s2. If no character is found, the function changes the saved pointer to a null pointer and returns it. If any character is found, the character becomes the first character of a token. * If the first character of a token is found, the function searches for any characters contained in the string s2 after the first character of the token. If none of the characters is found, the function changes the saved pointer to a null pointer. If any of the characters is found, the character is overwritten by a null character and a pointer to the next character becomes a pointer to be saved. * The function returns a pointer to the first character of the token.
244
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
6-12 memset
Character String/Memory Functions
FUNCTION The memory function memset initializes a specified number of bytes in an object in memory with a specified character. HEADER string.h FUNCTION PROTOTYPE void *memset (void *s, int c, size_t
n);
Function memset
Arguments s ... Pointer to object in memory to be initialized c ... Character whose value is to be assigned to each byte n ... Number of bytes to be initialized
Return Value Value of s
EXPLANATION * The memset function first converts the character specified by c to unsigned char and then assigns the value of this character to the n number of bytes from the beginning of the object pointed to by s.
User's Manual U14872EJ1V0UM
245
CHAPTER 10
LIBRARY FUNCTIONS
6-13 strerror
Character String/Memory Functions
FUNCTION The strerror function returns a pointer to the location which stores a string describing the error message associated with a given error number. HEADER string.h FUNCTION PROTOTYPE char *strerror (int errnum);
Function strerror
Arguments errnum ... Error number
Return Value * Pointer to string describing error message if message associated with error number exists * Null pointer if no message associated with error number exists
EXPLANATION * The strerror function returns a pointer to one of the following strings associated with the value of errnum. 0....................... "Error 0" 1 (EDOM)......... "Argument too large" 2 (ERANGE) .... "Result too large" 3 (ENOMEM) ... "Not enough memory" Otherwise, the function returns a null pointer.
246
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
6-14 strlen
Character String/Memory Functions
FUNCTION The string function strlen returns the length of a character string. HEADER string.h FUNCTION PROTOTYPE size_t strlen (const char *s);
Function strlen
Arguments s... Pointer to character string
Return Value Length of string s
EXPLANATION * The strlen function returns the length of the null terminated string pointed to by s.
User's Manual U14872EJ1V0UM
247
CHAPTER 10
LIBRARY FUNCTIONS
6-15 strcoll
Character String/Memory Functions
FUNCTION strcoll compares two character strings based on the information specific to the area. HEADER string.h FUNCTION PROTOTYPE int strcoll (const char *s1, const char *s2) ;
Function strcoll
Arguments s1 ... Pointer to comparison character string s2 ... Pointer to comparison character string
Return Value When character strings s1 and s2 are equal ... 0 When character strings s1 and s2 are different ... The difference between the values whose first different characters are converted to int (character of s1 - character of s2)
EXPLANATION * This compiler does not support operations specific to the cultural sphere. The operations are the same as that of strcmp.
248
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
6-16 strxfrm
Character String/Memory Functions
FUNCTION strxfrm converts a character string based on the information specific to the area. HEADER string.h FUNCTION size_t strxfrm (char *s1, const char *s2, size_t n) ;
Function strxfrm
Arguments s1 ... Pointer to a compared character string s2 ... Pointer to a compared character string n ... Maximum number of characters in s1
Return Value Returns the length of the character string of the result of the conversion (does not include a character string to indicate the end) If the returned value is n or more, the contents of the array indicated by s1 is undefined.
EXPLANATION * This compiler does not support operations specific to the cultural sphere. The operations are the same as those of the following functions. strncpy (s1, s2, c) ; return (strlen (s2)) ;
User's Manual U14872EJ1V0UM
249
CHAPTER 10
LIBRARY FUNCTIONS
7-1
acos (normal model only)
Mathematical Functions
FUNCTION acos finds acos. HEADER math.h FUNCTION PROTOTYPE double acos (double x) ;
Function acos
Arguments x ... Numeric value on which operation is performed
Return Value When -1 x 1 ... acos of x When x < -1, 1 < x, x = NaN ... NaN
EXPLANATION * Calculates acos of x (range between 0 and p). * When x is non-numeric, NaN is returned. * In the case of the definition area error of x < -1, 1 < x, NaN is returned and EDOM is set.
250
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-2
asin (normal model only)
Mathematical Functions
FUNCTION asin finds asin. HEADER math.h FUNCTION PROTOTYPE double asin (double x) ;
Function asin
Arguments x ... Numeric value on which operation is performed
Return Value When -1 x 1 ... asin of x When x -1, 1 x, x = NaN ... NaN When x = -0 ... -0 When underflow occurs ... Non-normalized number
EXPLANATION * Calculates asin (range between -/2 and +/2) of x. * In the case of area error of x < -1, 1 < x, NaN is returned and EDOM is set to errno. * When x is non-numeric, NaN is returned. * When x is -0, -0 is returned. * If an underflow occurs as a result of conversion, a non-normalized number is returned.
User's Manual U14872EJ1V0UM
251
CHAPTER 10
LIBRARY FUNCTIONS
7-3
atan (normal model only)
Mathematical Functions
FUNCTION atan finds atan. HEADER math.h FUNCTION PROTOTYPE double atan (double x) ;
Function atan
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... atan of x When x = NaN ... NaN When x = -0 ... -0
EXPLANATION * Calculates atan (range between -/2 and +/2) of x. * When x is non-numeric, NaN is returned. * When x is -0, -0 is returned. * If an underflow occurs as a result of conversion, a non-normalized number is returned.
252
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-4
atan2 (normal model only)
Mathematical Functions
FUNCTION atan2 finds atan of y/x. HEADER math.h FUNCTION PROTOTYPE double atan2 (double y, double x) ;
Function atan2
Arguments x ... Numeric value on which operation is performed y ... Numeric value on which operation is performed
Return Value Normal ... atan of y/x When both x and y are 0 or y/x is the value that cannot be expressed, or either x or y is NaN and both x and y are ... NaN Non-normalized number ... When underflow occurs
EXPLANATION * atan (range between - and +) of y/x is calculated. When both x and y are 0 or y/x is the value that cannot be expressed, or when both x and y are infinite, NaN is returned and EDOM is set to errno. * If either x or y is non-numeric, NaN is returned. * If an underflow occurs as a result of operation, a non-normalized number is returned.
User's Manual U14872EJ1V0UM
253
CHAPTER 10
LIBRARY FUNCTIONS
7-5
cos (normal model only)
Mathematical Functions
FUNCTION cos finds cos. HEADER math.h FUNCTION PROTOTYPE double cos (double x) ;
Function cos
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... cos of x When x = NaN, x = ... NaN
EXPLANATION * Calculates cos of x. * If x is non-numeric, NaN is returned. * If x is infinite, NaN is returned and EDOM is set to errno. * If the absolute value of x is extremely large, the result of an operation becomes an almost meaningless value.
254
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-6
sin (normal model only)
Mathematical Functions
FUNCTION sin finds sin. HEADER math.h FUNCTION PROTOTYPE double sin (double x) ;
Function sin
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... sin of x When x = NaN, x = ... NaN When underflow occurs ... Non-normalized number
EXPLANATION * Calculates sin of x. * If x is non-numeric, NaN is returned. * If x is infinite, NaN is returned and EDOM is set to errno. * If an underflow occurs as a result of operation, a non-normalized number is returned. * If the absolute value of x is extremely large, the result of an operation becomes an almost meaningless value.
User's Manual U14872EJ1V0UM
255
CHAPTER 10
LIBRARY FUNCTIONS
7-7
tan (normal model only)
Mathematical Functions
FUNCTION tan finds tan. HEADER math.h FUNCTION PROTOTYPE double tan (double x) ;
Function tan
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... tan of x When x = NaN, x = ... NaN When underflow occurs ... Non-normalized number
EXPLANATION * Calculates tan of x. * If x is non-numeric, NaN is returned. * If x is infinite, NaN is returned and EDOM is set to errno. * If an underflow occurs as a result of operation, a non-normalized number is returned. * If the absolute value of x is extremely large, the result of an operation becomes an almost meaningless value.
256
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-8
cosh (normal model only)
Mathematical Functions
FUNCTION cosh finds cosh. HEADER math.h FUNCTION PROTOTYPE double cosh (double x) ;
Function cosh
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... cosh of x When overflow occurs, x = NaN, x = ... HUGE_VAL (with positive sign) x = NaN ... NaN
EXPLANATION * Calculates cosh of x. * If x is non-numeric, NaN is returned. * If x is infinite, a positive infinite value is returned. * If an overflow occurs as a result of the operation, HUGE_VAL with a positive sign is returned, and ERANGE is set to errno.
User's Manual U14872EJ1V0UM
257
CHAPTER 10
LIBRARY FUNCTIONS
7-9
sinh (normal model only)
Mathematical Functions
FUNCTION sinh finds sinh. HEADER math.h FUNCTION PROTOTYPE double sinh (double x) ;
Function sinh
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... sinh of x When x = NaN ... NaN When x = ... When overflow occurs ... HUGE_VAL (with the sign of the overflown value) When underflow occurs ... 0
EXPLANATION * Calculates sinh of x. * If x is non-numeric, NaN is returned. * If x is , is returned. * If an overflow occurs as a result of the operation, HUGE_VAL with the sign of the overflowed value is returned, and ERANGE is set to errno. * If an underflow occurs as a result of the operation, 0 is returned.
258
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-10 tanh (normal model only)
Mathematical Functions
FUNCTION tanh finds tanh. HEADER math.h FUNCTION PROTOTYPE double tanh (double x) ;
Function tanh
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... tanh of x When x = NaN ... NaN When x = ... 1 When underflow occurs ... 0
EXPLANATION * Calculates tanh of x. * If x is non-numeric, NaN is returned. * If x is , 1 is returned. * If an underflow occurs as a result of the operation, 0 is returned.
User's Manual U14872EJ1V0UM
259
CHAPTER 10
LIBRARY FUNCTIONS
7-11 exp (normal model only)
Mathematical
FUNCTION exp finds the exponent function. HEADER math.h FUNCTION PROTOTYPE double exp (double x) ;
Function exp
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... exponent function of x When x = NaN ... NaN When x = ... When overflow occurs ... HUGE_VQAL (with positive sign) When underflow occurs ... Non-normalized number When annihilation of valid digits occurs due to underflow ... +0
EXPLANATION * Calculates exponent function of x. * If x is non-numeric, NaN is returned. * If x is , is returned. * If an underflow occurs as a result of the operation, a non-normalized number is returned. * If annihilation of valid digits due to underflow occurs as a result of the operation, +0 is returned. * If an overflow occurs as a result of the operation, HUGE_VAL with a positive sign is returned and ERANGE is set to errno.
260
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-12 frexp (normal model only)
Mathematical Functions
FUNCTION frexp finds the mantissa and exponent part. HEADER math.h FUNCTION PROTOTYPE double frexp (double x, int *exp) ;
Function frexp
Arguments x ... Numeric value on which operation is performed exp ... Pointer to store exponent part
Return Value Normal ... mantissa of x When x = NaN, x = ... NaN When x = 0 ... 0
EXPLANATION * Divides a floating point number x by mantissa m and exponent n such as x = m*2^n and returns mantissa m. * Exponent n is stored where the pointer exp indicates. The absolute value of m, however, is 0.5 or more and less than 1.0. * If x is non-numeric, NaN is returned and the value of *exp is 0. * If x is infinite, NaN is returned, and EDOM is set to errno with the value of *exp as 0. * If x is 0, 0 is returned and the value of *exp is 0.
User's Manual U14872EJ1V0UM
261
CHAPTER 10
LIBRARY FUNCTIONS
7-13 ldexp (normal model only)
Mathematical Functions
FUNCTION ldexp finds x*2^exp. HEADER math.h FUNCTION PROTOTYPE double ldexp (double x, int exp) ;
Function exp
Arguments x ... Numeric value on which operation is performed exp ... Exponent
Return Value Normal ... x*2 ^ exp When x = NaN ... NaN When x = ... When x = 0 ... 0 When overflow occurs ... HUGE_VAL (with the sign of the overflown value) When underflow occurs ... Non-normalized number When annihilation of valid digits occurs due to underflow ... 0
EXPLANATION * Calculates x*2^exp. * If x is non-numeric, NaN is returned. * If x is , is returned. * If x is 0, 0 is returned. * If an overflow occurs as a result of the operation, HUGE_VAL with the overflowed value is returned and ERANGE is set to errno. * If an underflow occurs as a result of the operation, a non-normalized number is returned. * If annihilation of valid digits due to underflow occurs as a result of the operation, 0 is returned.
262
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-14 log (normal model only)
Mathematical Functions
FUNCTION log finds the natural logarithm. HEADER math.h FUNCTION PROTOTYPE double log (double x) ;
Function log
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... Natural logarithm of x When x 0 ... HUGE_VAL (with negative sign) When x is non-numeric ... NaN When x is infinite ... +
EXPLANATION * Finds the natural logarithm of x. * If x is non-numeric, NaN is returned. * If x is +, + is returned. * In the case of an area error of x < 0, HUGE_VAL with a negative sign is returned and EDOM is set to errno. * If x = 0, HUGE_VAL with a negative sign is returned, and ERANGE is set to errno.
User's Manual U14872EJ1V0UM
263
CHAPTER 10
LIBRARY FUNCTIONS
7-15 log10 (normal model only)
Mathematical Functions
FUNCTION log10 finds a logarithm with 10 as the base. HEADER math.h FUNCTION PROTOTYPE double log10 (double x) ;
Function log10
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... Logarithm with 10 of x as the base When x 0 ... HUGE_VAL (with negative sign) When x is non-numeric ... NaN When x is infinite ... +
EXPLANATION * Finds a logarithm with 10 of x as the base. * If x is non-numeric, NaN is returned. * If x is +, + is returned. * In the case of an area error of x < 0, HUGE_VAL with a negative sign is returned and EDOM is set to errno. * If x = 0, HUGE_VAL with a negative sign is returned, and ERANGE is set to errno.
264
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-16 modf (normal model only)
Mathematical Functions
FUNCTION modf finds the fraction part and integer part. HEADER math.h FUNCTION PROTOTYPE double modif (double x, double *iptr) ;
Function modif
Arguments x ... Numeric value on which operation is performed iptr ... Pointer to integer part
Return Value Normal ... Fraction part of x When x is non-numeric or infinite ... NaN When x is 0 ... 0
EXPLANATION * Divides a floating point number x by a fraction part and an integer part * Returns the fraction part with the same sign as that of x, and stores the integer part to the location indicated by the pointer iptr. * If x is non-numeric, NaN is returned and stored in the location indicated by the pointer iptr. * If x is infinite, NaN is returned and stored in the location indicated by the pointer iptr, and EDOM is set to errno. * If x = 0, 0 is stored in the location indicated by the pointer iptr.
User's Manual U14872EJ1V0UM
265
CHAPTER 10
LIBRARY FUNCTIONS
7-17 pow (normal model only)
Mathematical Functions
FUNCTION pow finds the yth power of x. HEADER math.h FUNCTION PROTOTYPE double pow (double x, double y) ;
Function pow
Arguments x ... Numeric value on which operation is performed y ... Multiplier
Return Value Normal ... x^y Either when x = NaN or y = NaN, x = + and y = 0 x < 0 and y integer, x < 0 and y = , x = 0 and y < 0 ... NaN When underflow occurs ... Non-normalized number When overflow occurs ... HUGE_VAL (with the sign of overflown value) When annihilation of valid digits occurs due to underflow ... 0
EXPLANATION * Calculates x^y. * If an overflow occurs as a result of the operation, HUGE_VAL with the sign of overflowed value is returned, and ERANGE is set to errno. * When x = NaN or y = NaN, NaN is returned. * When any of x = + and y = 0, x < 0 and y integer, x < 0 and y = or x = 0 and y 0, NaN is returned and EDOM is set to errno. * If an underflow occurs, a non-normalized number is returned. * If annihilation of valid digits occurs due to underflow, 0 is returned.
266
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-18 sqrt (normal model only)
Mathematical Functions
FUNCTION sqrt finds the square root. HEADER math.h FUNCTION PROTOTYPE double sqrt (double x) ;
Function sqrt
Arguments x ... Numeric value on which operation is performed
Return Value When x 0 ... Square root of x When x = 0 ... 0 When x < 0 ... NaN
EXPLANATION * Calculates the square root of x. * In the case of an area error of x < 0, 0 is returned and EDOM is set to errno. * If x is non-numeric, NaN is returned. * If x is 0, 0 is returned.
User's Manual U14872EJ1V0UM
267
CHAPTER 10
LIBRARY FUNCTIONS
7-19 ceil (normal model only)
Mathematical Function
FUNCTION ceil finds the minimum integer no less than x. HEADER math.h FUNCTION PROTOTYPE double ceil (double x) ;
Function ceil
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... The minimum integer no less than x When x is non-numeric or x = ... NaN When x = -0 ... +0 When the minimum integer no less than x cannot be expressed ... x
EXPLANATION * Finds the minimum integer no less than x. * If x is non-numeric, NaN is returned. * If x is -0, +0 is returned. * If x is infinite, NaN is returned and EDOM is set to errno. * If the minimum integer no less than x cannot be expressed, x is returned.
268
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-20 fabs (normal model only)
Mathematical Functions
FUNCTION fabs returns the absolute value of the floating-point number x . HEADER math.h FUNCTION PROTOTYPE double fabs (double x) ;
Function fabs
Arguments x ... Numeric value to find the absolute value
Return Value Normal ... Absolute value of x When x is non-numeric ... NaN When x = -0 ... +0
EXPLANATION * Finds the absolute value of x. * If x is non-numeric, NaN is returned. * If x is -0, +0 is returned.
User's Manual U14872EJ1V0UM
269
CHAPTER 10
LIBRARY FUNCTIONS
7-21 floor (normal model only)
Mathematical Functions
FUNCTION floor finds the maximum integer no more than x. HEADER math.h FUNCTION PROTOTYPE double floor (double x) ;
Function floor
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... The maximum integer no more than x When x is non-numeric or x = ... NaN When x = -0 ... +0 When the maximum integer no more than x cannot be expressed
EXPLANATION * Finds the maximum integer no more than x. * If x is non-numeric, NaN is returned. * If x is -0, +0 is returned. * If x is infinite, NaN is returned and EDOM is set to errno. * If the maximum integer no more than x cannot be expressed, x is returned.
270
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-22 fmod (normal model only)
Mathematical Functions
FUNCTION fmod finds the remainder of x/y. HEADER math.h FUNCTION PROTOTYPE double fmod (double x, double y) ;
Function fmod
Arguments x ... Numeric value on which operation is performed y ... Numeric value on which operation is performed
Return Value Normal ... Remainder of x/y When x is non-numeric or y is non-numeric, when y is 0, when x is ... NaN When x and y = ... x
EXPLANATION * Calculates the remainder of x/y expressed with x - i*y. i is an integer. * If y 0, the return value has the same sign as that of x and the absolute value is less than that of y. * If y is 0 or x = , NaN is returned and EDOM is set to errno. * If x is non-numeric or y is non-numeric, NaN is returned. * If y is infinite, x is returned unless x is infinite.
User's Manual U14872EJ1V0UM
271
CHAPTER 10
LIBRARY FUNCTIONS
7-23 matherr (normal model only)
Mathematical Functions
FUNCTION matherr performs exception processing of the library that deals with floating-point numbers. HEADER math.h FUNCTION PROTOTYPE void matherr (struct exception *x) ;
Function matherr
Arguments struct exception { int type; char *name; } type......Numeric value to indicate arithmetic exception name ...Function name None
Return Value
EXPLANATION * When an exception occurs, matherr is automatically called in the standard library and runtime library, which deal with floating-point numbers. * When called from the standard library, EDOM and ERANGE are set to errno. The following shows the relationship between the arithmetic exception type and errno.
Type 1 2 3 4 5 Arithmetic Exception Underflow Annihilation Overflow Zero division Inoperable Value Set to errno ERANGE ERANGE ERANGE EDOM EDOM
Original error processing can be performed by changing or creating matherr.
272
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-24 acosf (normal model only)
Mathematical Functions
FUNCTION acosf finds acos. HEADER math.h FUNCTION PROTOTYPE float acosf (float x) ;
Function acosf
Arguments x ... Numeric value on which operation is performed
Return Value When -1 x 1 ... acos of x When x -1, 1 < x, x = ... NaN
EXPLANATION * Calculates acos (range between 0 and ) of x. * If x is non-numeric, NaN is returned. * In the case of a definition area error of x -1, 1 x, NaN is returned and EDOM is set to errno.
User's Manual U14872EJ1V0UM
273
CHAPTER 10
LIBRARY FUNCTIONS
7-25 asinf (normal model only)
Mathematical Functions
FUNCTION asinf finds asin. HEADER math.h FUNCTION PROTOTYPE float asinf (float x) ;
Function asinf
Arguments x ... Numeric value on which operation is performed
Return Value When -1 x 1 ... asin of x When x -1, 1 < x, x = NaN ... NaN x = -0 ... -0 When underflow occurs ... Non-normalized number
EXPLANATION * Calculates asin (range between -/2 and +/2) of x. * If x is non-numeric, NaN is returned. * In the case of a definition area error of x -1, 1 x, NaN is returned and EDOM is set to errno. * If x = -0, -0 is returned. * If an underflow occurs as a result of operation, a non-normalized number is returned.
274
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-26 atanf (normal model only)
Mathematical Functions
FUNCTION atanf finds atan. HEADER math.h FUNCTION PROTOTYPE float atanf (float x) ;
Function atanf
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... atan of x When x = NaN ... NaN When x = -0 ... -0
EXPLANATION * Calculates atan (range between -/2 and +/2) of x. * If x is non-numeric, NaN is returned. * If x = -0, -0 is returned. * If an underflow occurs as a result of the operation, a non-normalized number is returned.
User's Manual U14872EJ1V0UM
275
CHAPTER 10
LIBRARY FUNCTIONS
7-27 atan2f (normal model only)
Mathematical Functions
FUNCTION atan2f finds atan of y/x. HEADER math.h FUNCTION PROTOTYPE float atan21 (float y, float x) ;
Function atan21
Arguments x ... Numeric value on which operation is performed y ... Numeric value on which operation is performed
Return Value Normal ... atan of y/x When both x and y are 0 or a value whose y/x cannot be expressed, or either x or y is NaN, both x and y are ... NaN When underflow occurs ... Non-normalized number
EXPLANATION * Calculates atan (range between - and +) of y/x. When both x and y are 0 or the value whose y/x cannot be expressed, or when both x and y are infinite, NaN is returned and EDOM is set to errno. * When either x or y is non-numeric, NaN is returned. * If an underflow occurs as a result of the operation, a non-normalized number is returned.
276
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-28 cosf (normal model only)
Mathematical Functions
FUNCTION cosf finds cos. HEADER math.h FUNCTION PROTOTYPE float cost (float x) ;
Function cosf
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... cos of x When x = NaN, x = ... NaN
EXPLANATION * Calculates cos of x. * If x is non-numeric, NaN is returned. * If x is infinite, NaN is returned and EDOM is set to errno. * If the absolute value of x is extremely large, the result of an operation becomes an almost meaningless value.
User's Manual U14872EJ1V0UM
277
CHAPTER 10
LIBRARY FUNCTIONS
7-29 sinf (normal model only)
Mathematical Functions
FUNCTION sinf finds sin. HEADER math.h FUNCTION PROTOTYPE float sinf (float x) ;
Function sinf
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... sin of x When x = NaN, x = ... NaN When underflow occurs ... Non-normalized number
EXPLANATION * Calculates sin of x. * If x is non-numeric, NaN is returned. * If x is infinite, NaN is returned and EDOM is set to errno. * If an underflow occurs as a result of the operation, a non-normalized number is returned. * If the absolute value of x is extremely large, the result of an operation becomes an almost meaningless value.
278
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-30 tanf (normal model only)
Mathematical Functions
FUNCTION tanf finds tan. HEADER math.h FUNCTION PROTOTYPE float tanf (float x) ;
Function tanf
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... tan of x When x = NaN, x = ... NaN When underflow occurs ... Non-normalized number
EXPLANATION * Calculates tan of x. * If x is non-numeric, NaN is returned. * If x is infinite, NaN is returned and EDOM is set to errno. * If an underflow occurs as a result of operation, a non-normalized number is returned. * If the absolute value of x is extremely large, the result of an operation becomes an almost meaningless value.
User's Manual U14872EJ1V0UM
279
CHAPTER 10
LIBRARY FUNCTIONS
7-31 coshf (normal model only)
Mathematical Functions
FUNCTION coshf finds cosh. HEADER math.h FUNCTION PROTOTYPE float coshf (float x) ;
Function coshf
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... cosh of x When overflow occurs, x = ... HUGE_VAL (with a positive sign) x = NaN ... NaN
EXPLANATION * Calculates cosh of x. * If x is non-numeric, NaN is returned. * If x is infinite, positive infinite value is returned. * If an overflow occurs as a result of the operation, HUGE_VAL with a positive sign is returned and ERANGE is set to errno.
280
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-32 sinhf (normal model only)
Mathematical Functions
FUNCTION sinhf finds sinh. HEADER math.h FUNCTION PROTOTYPE float sinhf (float x) ;
Function sinhf
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... sinh of x When overflow occurs ... HUGE_VAL (with a sign of the overflown value) x = NaN ... NaN When x = ... When underflow occurs ... 0
EXPLANATION * Calculates sinh of x. * If x is non-numeric, NaN is returned. * If x is , is returned. * If an overflow occurs as a result of the operation, HUGE_VAL with the sign of overflowed value is returned and ERANGE is set to errno. * If an underflow occurs as a result of the operation, 0 is returned.
User's Manual U14872EJ1V0UM
281
CHAPTER 10
LIBRARY FUNCTIONS
7-33 tanhf (normal model only)
Mathematical Functions
FUNCTION tanhf finds tanh. HEADER math.h FUNCTION PROTOTYPE float tanhf (float x) ;
Function tanhf
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... tanh of x x = NaN ... NaN When x = ... 1 When underflow occurs ... 0
EXPLANATION * Calculates tanh of x. * If x is non-numeric, NaN is returned. * If x is , 1 is returned. * If an underflow occurs as a result of the operation, 0 is returned.
282
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-34 expf (normal model only)
Mathematical Functions
FUNCTION expf finds the exponent function. HEADER math.h FUNCTION PROTOTYPE float expf (float x) ;
Function expf
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... Exponent function of x When overflow occurs ... HUGE_VAL (with positive sign) x = NaN ... NaN When x = ... When underflow occurs ... Non-normalized number When annihilation of effective digits occurs due to underflow ... +0
EXPLANATION * Calculates the exponent function of x. * If x is non-numeric, NaN is returned. * If x is , is returned. * If an overflow occurs as a result of the operation, HUGE_VAL with a positive sign is returned and ERANGE is set to errno. * If an underflow occurs as a result of the operation, a non-normalized number is returned. * If annihilation of valid digits occurs due to underflow as a result of the operation, +0 is returned.
User's Manual U14872EJ1V0UM
283
CHAPTER 10
LIBRARY FUNCTIONS
7-35 frexpf (normal model only)
Mathematical Functions
FUNCTION frexpf finds the mantissa and exponent parts. HEADER math.h FUNCTION PROTOTYPE float frexpf (float x, int *exp) ;
Function frexpf
Arguments x ... Numeric value on which operation is performed exp ... Pointer to store exponent part
Return Value Normal ... Mantissa of x When x = NaN, x = ... NaN When x = 0 ... 0
EXPLANATION * Divides a floating-point number x by mantissa m and exponent n such as x = m*2^n and returns mantissa m. * Exponent n is stored where the pointer exp indicates. The absolute value of m, however, is 0.5 or more and less than 1.0. * If x is non-numeric, NaN is returned and the value of *exp is 0. * If x is , NaN is returned, and EDOM is set to errno with the value of *exp as 0. * If x is 0, 0 is returned and the value of *exp is 0.
284
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-36 ldexpf (normal model only)
Mathematical Functions
FUNCTION ldexpf finds x*2^exp. HEADER math.h FUNCTION PROTOTYPE float ldexpf (float x, int exp) ;
Function ldexpf
Arguments x ... Numeric value on which operation is performed exp ... Exponent
Return Value Normal ... x*2^exp When x = NaN ... NaN When x = ... When x = 0 ... 0 When overflow occurs ... HUGE_VAL (with the sign of overflown value) When underflow occurs ... Non-normalized numberV When annihilation of valid digits occurs due to underflow ... 0
EXPLANATION * Calculates x*2^exp. * If x is non-numeric, NaN is returned. If x is , is returned. If x is 0, 0 is returned. * If an overflow occurs as a result of the operation, HUGE_VAL with the sign of overflowed value is returned and ERANGE is set to errno. * If an underflow occurs as a result of the operation, a non-normalized number is returned . * If annihilation of valid digits due to underflow occurs as a result of the operation, 0 is returned.
User's Manual U14872EJ1V0UM
285
CHAPTER 10
LIBRARY FUNCTIONS
7-37 logf (normal model only)
Mathematical Functions
FUNCTION logf finds the natural logarithm. HEADER math.h FUNCTION PROTOTYPE float logf (float x) ;
Function logf
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... Natural logarithm of x When x is non-numeric ... NaN When x is infinite ... + When x 0 ... HUGE_VAL (with negative sign)
EXPLANATION * Finds the natural logarithm of x. * If x is non-numeric, NaN is returned. * If x is +, + is returned. * In the case of an area error of x < 0, HUGE_VAL with a negative sign is returned, and EDOM is set to errno. * If x = 0, HUGE_VAL with a negative sign is returned, and ERANGE is set to errno.
286
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-38 log10f (normal model only)
Mathematical Functions
FUNCTION log10f finds a logarithm with 10 as the base. HEADER math.h FUNCTION PROTOTYPE float log10f (float x) ;
Function log10f
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... Logarithm with 10 of x as the base When x is non-numeric ... NaN When x = + ... + When x 0 ... HUGE_VAL (with negative sign)
EXPLANATION * Finds a logarithm with 10 of x as the base. * If x is non-numeric, NaN is returned. * If x is +, + is returned. * In the case of an area error of x < 0, HUGE_VAL with a negative sign is returned, and EDOM is set to errno. * If x = 0, HUGE_VAL with a negative sign is returned, and ERANGE is set to errno.
User's Manual U14872EJ1V0UM
287
CHAPTER 10
LIBRARY FUNCTIONS
7-39 modff (normal model only)
Mathematical Functions
FUNCTION modff finds the fraction part and integer part. HEADER math.h FUNCTION PROTOTYPE float modff (float x, float *iptr) ;
Function modff
Arguments x ... Numeric value on which operation is performed iptr ... Pointer for integer part
Return Value Normal ... Fraction part of x When x is non-numeric or infinite ... NaN When x = 0 ... 0
EXPLANATION * Divides a floating point number x by the fraction part and integer part. * Returns the fraction part with the same sign as that of x, and stores the integer part in the location indicated by the pointer iptr. * If x is non-numeric, NaN is returned and stored in the location indicated by the pointer iptr. * If x is infinite, NaN is returned and stored in the location indicated by the pointer iptr, and EDOM is set to errno. * If x = 0, 0 is returned and stored in the location indicated by the pointer iptr.
288
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-40 powf (normal model only)
Mathematical Functions
FUNCTION powf finds the yth power of x. HEADER math.h FUNCTION PROTOTYPE float powf (float x, float y) ;
Function powf
Arguments x ... Numeric value on which operation is performed y ... Multiplier
Return Value Normal ... x^y Either when = x = NaN or y = NaN x = + and y = 0 x < 0 and y integer, x < 0 and y = x = 0 and y 0 ... NaN When underflow occurs ... Non-normalized number When overflow occurs ... HUGE_VAL (with the sign of overflown value) When annihilation of valid digits occurs due to underflow ... 0
EXPLANATION * Calculates x^y. * If an overflow occurs as a result of the operation, HUGE_VAL with the sign of overflowed value is returned, and ERANGE is set to errno. * When x = NaN or y = NaN, NaN is returned. * When any of x = + and y = 0, x < 0 and y integer, x < 0 and y = , or x = 0 and y 0, NaN is returned and EDOM is set to errno. * If an underflow occurs, a non-normalized number is returned. * If annihilation of valid digits occurs due to underflow, 0 is returned.
User's Manual U14872EJ1V0UM
289
CHAPTER 10
LIBRARY FUNCTIONS
7-41 sqrtf (normal model only)
Mathematical Functions
FUNCTION sqrtf finds the square root. HEADER math.h FUNCTION PROTOTYPE float sqrtf (float x) ;
Function sqrtf
Arguments x ... Numeric value on which operation is performed
Return Value When x 0 ... Square root of x When x = 0 ... 0 When x < 0 ... NaN
EXPLANATION * Calculates the square root of x. * In the case of area error of x < 0, 0 is returned and EDOM is set to errno. * If x is non-numeric, NaN is returned. * If x is 0, 0 is returned.
290
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-42 ceilf (normal model only)
Mathematical Functions
FUNCTION ceilf finds the minimum integer no less than x. HEADER math.h FUNCTION PROTOTYPE float ceilf (float x) ;
Function ceilf
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... The minimum integer no less than x When x is non-numeric or x = ... NaN When x = -0 ... +0 When the minimum integer no less than x cannot be expressed ... x
EXPLANATION * Finds the minimum integer no less than x. * If x is non-numeric, NaN is returned. * If x is -0, +0 is returned. * If x is infinite, NaN is returned and EDOM is set to errno. * If the minimum integer no less than x cannot be expressed, x is returned.
User's Manual U14872EJ1V0UM
291
CHAPTER 10
LIBRARY FUNCTIONS
7-43 fabsf (normal model only)
Mathematical Functions
FUNCTION fabsf returns the absolute value of the floating point number x. HEADER math.h FUNCTION PROTOTYPE float fabsf (float x) ;
Function fabsf
Arguments x ... Numeric value to find the absolute value
Return Value Normal ... Absolute value of x When x is non-numeric ... NaN When x = -0 ... +0
EXPLANATION * Finds the absolute value of x. * If x is non-numeric, NaN is returned. * If x is -0, +0 is returned.
292
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
7-44 floorf (normal model only)
Mathematical Functions
FUNCTION floorf finds the maximum integer no more than x. HEADER math.h FUNCTION PROTOTYPE float floorf (float x) ;
Function floorf
Arguments x ... Numeric value on which operation is performed
Return Value Normal ... The maximum integer no more than x When x is non-numeric or infinite ... NaN When x = -0 ... +0 When the maximum integer no more than x cannot be expressed ... x
EXPLANATION * Finds the maximum integer no more than x. * If x is non-numeric, NaN is returned. * If x is -0, +0 is returned. * If x is infinite, NaN is returned and EDOM is set to errno. * If the maximum integer no more than x cannot be expressed, x is returned.
User's Manual U14872EJ1V0UM
293
CHAPTER 10
LIBRARY FUNCTIONS
7-45 fmodf (normal model only)
Mathematical Functions
FUNCTION fmodf finds the remainder of x/y. HEADER math.h FUNCTION PROTOTYPE float fmodf (float x, float y) ;
Function fmodf
Arguments x ... Numeric value on which operation is performed y ... Numeric value on which operation is performed
Return Value Normal ... Remainder of x/y When x is non-numeric or y is non-numeric When y is 0, when x is ... NaN When x and y = ... x
EXPLANATION * Calculates the remainder of x/y expressed with x - i*y. i is an integer. * If y 0, the return value has the same sign as that of x and the absolute value is less than y. * If y is 0 or x = , NaN is returned and EDOM is set to errno. * If x is non-numeric or y is non-numeric, NaN is returned. * If y is infinite, x is returned unless x is infinite.
294
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
8-1
_ _assertfail (normal model only)
Diagnostic Functions
FUNCTION _ _assertfail supports the assert macro. HEADER math.h FUNCTION PROTOTYPE int _ _assertfail (char*_ _msg, char*_ _cond, char*_ _file, int_ _line) ;
Function _ _assertfail
Arguments _ _msg ... Pointer to character string to indicate output conversion specification to be passed to printf function _ _cond ... Actual argument of assert macro _ _file ... Source file name _ _line ... Source line number
Return Value Undefined
EXPLANATION * The _ _assertfail function receives information from the assert macro (refer to 10.2 Headers (13) assert.h), calls the printf function, outputs information, and calls the abort function. * The assert macro adds diagnostic functions to a program. When the assert macro is executed, if p is false (equal to 0), the assert macro passes information related to the specific call that has brought the false value (actual argument text, source file name, and source line number are included in the information. The other two are the values of macro _ _FILE_ _ and _ _LINE_ _) to the _ _assertfail function.
User's Manual U14872EJ1V0UM
295
CHAPTER 10
LIBRARY FUNCTIONS
10.5 Batch Files for Update of Startup Routine and Library Functions
This compiler is provided with batch files for updating a part of the standard library functions and the startup routine. The batch files in the BAT directory are shown in Table 10-12 below. Caution The file d9026.78k in the BAT directory is used during batch file activation for updating the library, not for development. When developing a system, it is necessary to have a device file (sold separately). Table 10-12. Batch Files for Updating Library Functions
Batch File mkstup.bat Application Updates the startup routine (cstart[n].asm). When changing the startup routine, perform assembly using this batch file. Updates the firmware ROM termination routine (rom.asm). When changing rom.asm, update the library using this batch file. Updates the getchar function. The default assumption sets P0 of the SFR to input port. When it is necessary to change this setting, change the defined value of EQU of PORT in getchar.asm and update the library using this batch file. repputc.bat Updates the putchar function. The default assumption sets P0 of the SFR to output port. When it is necessary to change this setting, change the defined value of EQU of PORT in putchar.asm and update the library using this batch file. repputcs.bat Updates the putchar function to SM78K0S-supporting. When it is necessary to check the output of the putchar function using the SM78K0S, update the library using this batch file. repselo.bat Saves/restores the reserved area of the compiler (_@KREGxx) as part of the save/restore processing of the setjmp/longjmp functions (the default assumption is to not save/restore). Update the library using this batch file when the -QR option is specified. Does not save/restore the reserved area of the compiler (_@KREGxx) as part of the save/restore processing of the setjmp/longjmp functions (the default assumption is to not save/restore). Update the library using this batch file when the -QR option is not specified.
reprom.bat
repgetc.bat
repselon.bat
296
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
10.5.1 Using batch files Use the batch files in the subdirectory BAT. Because these files are the batch files used to activate the assembler and librarian, an environment in which the assembler package RA78K0S Ver.1.30 or later operates is necessary. Before using the batch files, set the directory that contains the RA78K0S execution format file using the environment variable PATH. Create a subdirectory (LIB) of the same level as BAT for the batch files and put the post-assembly files in this subdirectory. When a C startup routine or library is installed in a subdirectory LIB that is the same level as BAT, these files are overwritten. To use the batch files, move the current directory to the subdirectory BAT and execute each batch file. At this time, the following parameters are necessary. Product type = chiptype (classification of target chip) 9026 *** PD789026, etc. The following is an illustration of how to use each batch file. The batch file for: (1) Startup routine * For PC-9800 series, IBM PC/AT and compatibles mkstup chiptype Example mkstup 9026
* For HP9000 series 700TM, SPARCstationTM Family /bin/sh mkstup.sh chiptype Example /bin/sh mkstup.sh 9026
(2) Firmware ROM routine update * For PC-9800 series, IBM PC/AT and compatibles reprom chiptype Example reprom 9026
* For HP9000 series 700, SPARCstation Family /bin/sh reprom.sh chiptype Example /bin/sh reprom.sh 9026
User's Manual U14872EJ1V0UM
297
CHAPTER 10
LIBRARY FUNCTIONS
(3) getchar function update * For PC-9800 series, IBM PC/AT and compatibles repgetc chiptype Example repgetc 9026
* For HP9000 series 700, SPARCstation Family /bin/sh repgetc.sh chiptype Example /bin/sh repgetc.sh 9026
(4) putchar function update * For PC-9800 series, IBM PC/AT and compatibles repputc chiptype Example repputc 9026
* For HP9000 series 700, SPARCstation Family /bin/sh repputc.sh chiptype Example /bin/sh repputc.sh 9026
(5) putchar function (SM78K0S-supporting) update * For PC-9800 series, IBM PC/AT and compatibles repputcs chiptype Example repputcs 9026
* For HP9000 series 700, SPARCstation Family /bin/sh repputcs.sh chiptype Example /bin/sh repputcs.sh 9026
298
User's Manual U14872EJ1V0UM
CHAPTER 10
LIBRARY FUNCTIONS
(6) setjmp/longjmp function update (with restore/save processing) * For PC-9800 series, IBM PC/AT and compatibles repselo chiptype Example repselo 9026
* For HP9000 series 700, SPARCstation Family /bin/sh repselo.sh chiptype Example /bin/sh repselo.sh 9026
(7) setjmp/longjmp function update (without restore/save processing) * For PC-9800 series, IBM PC/AT and compatibles repselon chiptype Example repselon 9026
* For HP9000 series 700, SPARCstation Family /bin/sh repselon.sh chiptype Example /bin/sh repselon.sh 9026
User's Manual U14872EJ1V0UM
299
CHAPTER 11
EXTENDED FUNCTIONS
This chapter describes the extended functions unique to this C compiler and not specified in the ANSI (American National Standards Institute) Standard for C. The extended functions of this C compiler are used to generate codes for effective utilization of the target devices in the 78K/0S Series. Not all of these extended functions are always effective. Therefore, it is recommended to use only the effective ones according to the user's purpose. For the effective use of the extended functions, refer to CHAPTER 13 EFFECTIVE UTILIZATION OF COMPILER along with this chapter. C source programs created by using the extended functions of the C compiler utilize microcontroller-dependent functions. As regards portability to other microcontrollers, they are compatible at the C language level. For this reason, C source programs developed by using these extended functions are portable to other microcontrollers with easy-to-make modifications. Remark In the explanation of this chapter, "RTOS" stands for the 78K/0 Series real-time OS.
300
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
11.1 Macro Names
This C compiler has two types of macro names: those indicating the series names for target devices and those indicating device names (processor types). These macro names are specified according to the option at compilation to output object code for a specific target device or according to the processor type in the C source. In the example below, _ _K0S_ _ and _ _9026_ are specified. For details of these macro names, see 9.8 Predefined Macro Names. [Example] Compile option >CC78K0S
-C9026
prime.c ...
Specification of device type: #pragma pc (9026)
User's Manual U14872EJ1V0UM
301
CHAPTER 11
EXTENDED FUNCTIONS
11.2 Keywords
The following tokens have been added to this C compiler as keywords to realize the extended functions. As with ANSI-C keywords, these tokens cannot be used as labels or variable names. All the keywords must be described in lowercase letters. A keyword containing uppercase letters, is not interpreted as such by the C compiler. The following shows the list of keywords added to this compiler. Of these keywords, ones not starting with "_ _" can be disabled by specifying the option (-ZA) that enables only ANSI-C language specifications (for the ANSI-C keywords, refer to 2.2 Keywords). Table 11-1. List of Added Keywords
Keyword _ _callt _ _callf
Note
Use callt/_ _callt functions _ callf/_ _callf functions _ sreg/_ _sreg variables _ noauto functions norec/_ _leaf functions _ boolean type/_ _boolean type variables _ bit type variables Hardware interrupt
callt callf sreg noauto
_ _sreg
_ _leaf _ _boolean
norec boolean bit
_ _interrupt _ _interrupt_brk _
Note Note
Software interrupt Bank function ASM statements
_ _banked 1 to 15 _ _asm _ _rtos_interrupt _ _ _pascal _ _directmap _ _temp
Note
Handler to allocate for RTOS Pascal function Absolute address allocation specification Temporary variable
Note A warning is output for the descriptions callf, _ _callf, _ _interrupt_brk, _ _banked 1 to 15, and _ _rtos_interrupt and they are ignored. (1) Functions The keywords callt, _ _callt, noauto, norec, _ _leaf, _ _interrupt, and _ _pascal are attribute qualifiers. These keywords must be described before any function declaration. The format of each attribute qualifier is shown below. attribute qualifier ordinary declarator function name (parameter type list/identifier list) [Example] _ _callt int func (int);
Attribute qualifier specifications are limited to those listed below. (The noauto and norec/_ _leaf qualifiers cannot be specified at the same time.) callt and _ _callt, callf and _ _callf, norec and _ _leaf are regarded as the same specifications. However, the qualifiers with `_ _' added are enabled even when the -ZA option is specified.
302
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
* callt * noauto * norec * callt noauto * callt norec * noauto callt * norec callt * _ _interrupt * _ _pascal * _ _pascal noauto * _ _pascal callt * noauto _ _pascal * callt _ _pascal * callt noauto _ _pascal
(2) Variables * The same regulations apply to the sreg or _ _sreg specification as to register in C language (refer to 11.5 (3) How to use the saddr area for details). * The same regulations apply to the bit, boolean or _ _boolean specification as to the char or int type specifier in C language. However, these types can be specified only for the variables defined outside a function (external variables). * The same regulations apply to the _ _directmap specification as to the type qualifier in C language (refer to 11.5 (31) Absolute address allocation specification for details). * The same regulations apply to the _ _temp specification as to the type qualifier in C language (refer to 11.5 (33) Temporary variables for details).
User's Manual U14872EJ1V0UM
303
CHAPTER 11
EXTENDED FUNCTIONS
11.3 Memory
The memory model is determined by the memory space of the target device. (1) Memory model Since memory space is a maximum of 64 KB, the model is 64 KB with code division and data division combined. (2) Register bank There is no register bank. (3) Memory space This C compiler uses memory space as shown below.
304
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Table 11-2. Utilization of Memory Space (a) Normal model (default)
Address 00 FE FE FE FE FE FF 40 to 7FH 20 to D7H D8 to E7H E8 to EFH F0 to F7H F8 to FFH 00 to FFH CALLT table sreg variables, boolean type variables Register variablesNote 1 Arguments of norec functionsNote 2 Automatic variables of norec functionsNote 3 Arguments of runtime libraryNote 4 sfr variables Use Size (bytes) 64 184 16 8 8 8 256
(b) Static model (at -SM16 specification)
Address 00 FE FE FE 40 to 7FH 20 to EFH F0 to FFH Consecutive areas between 20 and FFH 00 to FFH CALLT table sreg variables, boolean type variables Shared areaNote 5 For arguments, automatic variables, and workNote 6 Use Size (bytes) 64 208 16 8
FF
sfr variables
256
Notes 1. Area not used for register variables is used for sreg variables and boolean type variables. 2. If not completely used for register variables, area not used for norec function arguments is used for sreg variables and boolean type variables. 3. If not completely used for register variables and norec function arguments, area not used for norec function automatic variables is used for sreg variables and boolean type variables. 4. If not completely used for register variables and norec function arguments/automatic variables, area not used for runtime library arguments is used for sreg variables and boolean type variables. 5. The area used by the compiler varies depending on the parameters of the -SM option. Area not used as shared area is used for sreg variables and boolean type variables. 6. Valid only when the static model expansion specification option (-ZM) is specified. Remark If the register variable optimization option (-QR) is not specified, the area in Notes 1 to 3 is always used for sreg variables and boolean type variables.
User's Manual U14872EJ1V0UM
305
CHAPTER 11
EXTENDED FUNCTIONS
11.4 #pragma Directive
The #pragma directive is one of the preprocessing directives supported by ANSI. The #pragma directive,
depending on the character string to follow #pragma, instructs the compiler to translate using the method determined by the compiler. If the compiler does not support the #pragma directive, the #pragma directive is ignored and compilation is continued. If keywords are added by the directive, an error is output if the C source includes the keywords. In order to avoid this, the keywords in the C source should either be deleted or sorted by the #ifdef directive. This C compiler supports the following #pragma directives to realize the extended functions. The keywords specified after #pragma can be described either in uppercase or lowercase letters. For the extended functions using #pragma directives, refer to 11.5 How to Use Extended Functions.
306
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Table 11-3. List of #pragma Directives
#pragma Directive #pragma sfr #pragma asm #pragma vect #pragma interrupt #pragma di #pragma ei #pragma halt #pragma stop #pragma nop #pragma access #pragma section Applications Describes SFR name in C 11.5 (4) How to use the sfr area Inserts ASM statement in C source 11.5 (8) ASM statements Describes interrupt processing in C 11.5 (9) Interrupt functions Describes DI/EI instructions in C 11.5 (11) Interrupt functions Describes CPU control instructions in C 11.5 (12) CPU control instruction
Uses absolute address access functions 11.5 (13) Absolute address access function Changes compiler output section name and specifies section location 11.5 (15) Changing compiler output section name Changes module name 11.5 (17) Module name changing function Uses rotate function 11.5 (18) Rotate function Uses multiplication function 11.5 (19) Multiplication function Uses division function 11.5 (20) Division function Uses BCD operation function 11.5 (21) BCD operation function Uses data insertion function 11.5 (22) Data insertion function Uses register direct reference function 11.5 (29) Register direct reference function Expands the standard library functions memcpy and memset inline 11.5 (30) Memory manipulation function
#pragma name #pragma rot #pragma mul #pragma div #pragma bcd #pragma opc #pragma realregister #pragma inline
User's Manual U14872EJ1V0UM
307
CHAPTER 11
EXTENDED FUNCTIONS
11.5 How to Use Extended Functions
This section describes each of these extended functions in the following format. FUNCTION: Outlines the function that can be implemented with the extended function. EFFECT: Explains the effect brought about by the extended function. USAGE: Explains how to use the extended function. EXAMPLE: Indicates an application example of the extended function. RESTRICTIONS: Explains restrictions, if any, on the use of the extended function. EXPLANATION: Explains the above application example. COMPATIBILITY: Explains the compatibility of a C source program developed by another C compiler when it is to be compiled with this C compiler.
308
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(1) callt functions
callt Functions
callt/_ _callt _
FUNCTION * The callt instruction stores the address of a function to be called in an area [40H to 7FH] called the callt table, so that the function can be called with a shorter code than the one used to call the function directly. * To call a function declared by the callt (or _ _ callt) (called the callt function), a name with ? prefixed to the function name is used. To call the function, the callt instruction is used. * The function to be called does not differ from an ordinary function. EFFECT The object code can be shortened. USAGE Add the callt/_ _ callt attribute to the function to be called as follows (described at the beginning). callt extern type-name function-name
_ _callt extern type-name function-name
EXAMPLE _ _callt void func1 (void) ; _ _callt void func1 (void) { . . . /* function body */ . . . }
User's Manual U14872EJ1V0UM
309
CHAPTER 11
EXTENDED FUNCTIONS
callt Functions
callt/_ _callt _
RESTRICTIONS * The address of each function declared with callt/_ _ callt will be allocated to the callt table when object modules are linked. For this reason, when using the callt table in an assembler source module, the routine to be created must be made "relocatable" using symbols. * A check on the number of callt functions is made at linking. * When the -ZA option is specified, _ _callt is enabled and callt is disabled. * The area of the callt table is 40H to 7FH. * When the callt table is used exceeding the number of permitted callt attribute functions, a compile error will occur. * The callt table is used by specifying the -QL option. For that reason, the number of callt attributes permitted per load module and the total in the linking modules is as shown in Table 11-4. * When the option for using the library that supports prologue/epilogue (-ZD option) is specified, the -QL4 option cannot be used. Also, because two callt entries are used by the library that supports prologue/epilogue in the case of a normal model and up to ten in the case of a static model, the maximum number of callt entries is reduced by two in the case of a normal model and by up to ten in the case of a static model. Table 11-4. The Number of callt Attribute Functions That Can Be Used When the -QL Option Is Specified * When QQ option is not specified simultaneously
Option Normal model Static model -QL1 30 30 -QL2 27 29 -QL3 13 15 -QL4 0 12
* When QQ option is specified simultaneously
Option Normal model Static model -QL1 30 30 -QL2 27 29 -QL3 18 20 -QL4 11 13
* Cases where the -QL option is not used and the defaults are as shown below. Table 11-5. Restrictions on callt Function Usage
callt Function Number per load module Total number in linked module Restriction Value 30 max. 30 max.
310
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
EXAMPLE (C source) ============ ca1.c ============ _ _callt extern int tsub ( ); void main ( ) { int ret_val; ret_val = tsub ( ); } (Output object of compiler) ca1 module EXTRN callt ca2 module PUBLIC PUBLIC @@CALT CSEG ?tsub: DW @@CODE CSEG _tsub: . . . function body . . . ; Function definition _tsub ?tsub CALLT0 _tsub ; Declaration ; ; Allocation to segment ?tsub [?tsub] ; Declaration ; Call } _ _callt int tsub ( ) { int val; return val;
============ ca2.c ============
EXPLANATION * The callt attribute is given to the function tsub() so that it can be stored in the callt table. COMPATIBILITY * The C source program need not be modified if the keyword callt/_ _ callt is not used. * To change functions to callt functions, observe the procedure described in the USAGE above. * #define must be used. For details, see 11.6 Modifications of C Source.
User's Manual U14872EJ1V0UM
311
CHAPTER 11
EXTENDED FUNCTIONS
(2) Register variables
Register Variables
register
FUNCTION * Allocates the declared variables (including arguments of function) to the register (HL) and saddr area (_@KREG00 to _@KREG15). Saves and restores registers or saddr area during the preprocessing/ postprocessing of the module that declared a register. * The allocation is performed based on the number of times referenced. Therefore, it is undetermined to which register or saddr area the register variable is allocated. * For details of register variable allocation, refer to 11.7 Function Call Interface. * Register variables are allocated to different areas depending on the compile condition as shown below (for each option, refer to the CC78K0S C Compiler Operation (U14871E)). 1. In the case of the normal model, the register variables are allocated based on the number of times referenced to register HL or the saddr area [FED0H to FEDFH]. If there is no stack frame, register variables are allocated to register HL. allocated to the saddr area. 2. In the case of the static model, the register variables are allocated to register DE or _@KREGxx secured by -SM specification according to the number of times referenced. Only when the -ZM2 option is specified, register variables are allocated to the _@KREGxx. For details of the -ZM2 option, refer to 11.5 (32) Static model expansion specifications. EFFECT * Instructions to the variables allocated to the registers or saddr area are generally shorter in code length than those to memory. This helps shorten object code and also improves program execution speed. USAGE Declare a variable with the register storage class specifier as follows. register type-name variable-name Only when the -QR option is specified, register variables are
EXAMPLE void main (void) { register unsigned char c ; . . . }
312
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Register Variables
register
RESTRICTIONS * If register variables are not used so frequently, object code may increase (depending on the size and contents of the source). * Register variable declarations may be used for char/int/short/long/float/double/long double and pointer data types. (Normal model) * char uses half the area of other types. long/float/double/long double use twice the area. Between char types there are byte boundaries but in other cases, there are word boundaries. * In the case of int/short and pointers, a maximum of 8 variables per function is usable. From the 9th variable, the register variables are assigned to the normal memory. * In the case of a function without a stack frame, a maximum of 8 variables per function is usable for int/short and pointers. From the 9th variable, the register variables are assigned to the normal memory. (Static model) * char uses half the area of other types. * In the case of int/short and pointers, a maximum of 1 variable per function is usable. * From the 2nd variable, the register variables are assigned to the normal memory. * The register variables are invalid for long/float/double/long double.
Table 11-6. Restrictions on Register Variable Usage
Data Type Normal Model int/short Pointer 8 variables max. 8 variables max. (9 variables max. if function without stack frame) Usable Number (per Function) Static Model 1 variable max. 1 variable max.
User's Manual U14872EJ1V0UM
313
CHAPTER 11
EXTENDED FUNCTIONS
Register Variables
register
EXAMPLE (C source) void func (); void main () { register int i, j; i = 0; i += j; func (); } j = 1;
(Output object of compiler) * When the -SM option is not specified (example of register variable allocation to register HL and the saddr area) The following labels are declared by the startup routine (refer to APPENDIX A LIST OF LABELS FOR saddr AREA). EXTRN _main: push movw push movw movw incw movw xch add xch addc movw call pop movw pop ret hl ax, _@KREG14 ax hl, #00H ax, hl ax _@KREG14,ax a, x a, l a, x a, l hl, ax !_func ax _@KREG00, ax hl ; Saves the contents of the register at the beginning of the function ; Saves the contents of the saddr at the beginning of the function ; ; The following codes are output in the middle of the function ; ; ; ; ; ; ; ; ; ; Restores contents of the saddr at the end of the function ; ; Restores contents of the register at the end of the function _@KREG00 ; References the saddr area to be used
314
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Register Variables
register
* When the -SM option is specified (Example of register variable allocation to register DE) _main: push movw movw incw movw xch mov add xch addc mov call pop ret de de, #00H; 0 de, ax ax !?L0003+1, a a, x !?L0003, a a, e a, x a, d de, ax !_func de ; Restores the contents of the register at the end of the function ; Saves the contents of the register at the beginning of the function ; ; ; ; ; ; ; ; ; ;
EXPLANATION * To use register variables, you only need to declare them with the register storage class specifier. * Labels such as _@KREG00 include the modules declared with PUBLIC in the library attached to this C compiler. COMPATIBILITY * The C source program need not be modified if the other C compiler supports register declarations. * To change to register variables, add the register declarations for the variables to the program. * The C source program need not be modified if the other compiler supports register declarations. * How many variable registers can be used and to which area they will be allocated depends on the implementations of the other C compiler.
User's Manual U14872EJ1V0UM
315
CHAPTER 11
EXTENDED FUNCTIONS
(3) How to use the saddr area
Usage of saddr Area
sreg/_ _sreg
(1) Usage with sreg declaration FUNCTION * The external variables and in-function static variables (called sreg variables) declared with the keyword sreg or _ _sreg are automatically allocated to the saddr area [FE20H to FED7H] (normal model) and [FE20H to FEEFH] (static model) with relocatability. When those variables exceed the area shown above, a compile error occurs. * The sreg variables are treated in the same manner as the ordinary variables in the C source. * Each bit of sreg variables of char, short, int, and long type become boolean type variables automatically. * sreg variables declared without an initial value take 0 as the initial value. * The area that can be referenced by the sreg variables declared in the assembler source is the saddr area [FE20H to FEFFH]. The area [FED8H to FEFFH] (normal model) and [FEF0H to FEFFH] (static model) are used by compiler, so care must be taken (refer to Table 11-2 Utilization of Memory Space). EFFECT * Instructions to the saddr area are generally shorter in code length than those to memory. This helps shorten object code and also improves program execution speed. USAGE * Declare variables with the keywords sreg and _ _sreg inside a module and a function which defines the variables. Only variables with a static storage class specifier can become sreg variables inside a function. sreg type-name variable-name / sreg static type-name variable-name _ _sreg type-name variable-name / _ _sreg static type-name variable-name
* Declare the following variables inside a module that refers to sreg external variables. They can be described inside a function as well. extern sreg type-name variable-name / extern _ _sreg type-name variable-name
316
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Usage of saddr Area
sreg/_ _sreg
RESTRICTIONS * If const type is specified, or if sreg/_ _sreg is specified for a function, a warning message is output, and the sreg declaration is ignored. * char type uses a half the space of other types and long/float/double/long double types use twice the space of other types. * Between char types there are byte boundaries, but in other cases, there are word boundaries. * When -ZA is specified, only _ _sreg is enabled and sreg is disabled. * In the case of int/short and pointers, a maximum of 92 variables per load module is usable (when saddr area [FE20H to FED7H] is used). Note that the number of usable variables decreases when bit and boolean type variables, register variables, or norec and noauto functions are used (normal model). * In the case of int/short and pointers, a maximum of 104 variables per load module is usable (when saddr area [FE20H to FEEFH] is used). Note that the number of usable variables decreases when bit, boolean type variables, and shared areas are used (static model).
The following shows the maximum number of sreg variables that can be used per load module. Table 11-7. Restrictions on sreg Variable Usage
Data Type Usable Number of sreg Variables (per Load Module) When saddr Area [FE20H to FED7H] is Used int/short, pointer 92 variables max.
Note
When saddr Area [FE20H to FEEFH] is Used 104 variables max.
Note
Note When bit and boolean type variables are used, the usable number decreases. EXAMPLE (C source) extern sreg int hsmm0; extern sreg int hsmm1; extern sreg int *hsptr; void main ( } ){
hsmm0 -= hsmm1;
User's Manual U14872EJ1V0UM
317
CHAPTER 11
EXTENDED FUNCTIONS
Usage of saddr Area
sreg/_ _sreg
(Assembler source) The following example shows a definition code for an sreg variable created by the user. If an extern declaration is not made in the C source, the C compiler outputs the following codes. In this case, the ORG quasi-directive will not be output. PUBLIC PUBLIC PUBLIC @@DATS _hsmm0: _hsmm1: _hsptr: DSEG ORG DS DS DS _hsmm0 _hsmm1 _hsptr SADDRP 0FE20H (2) (2) (2) ; Declaration ; ; ; Allocation to segment ; ; ; ;
(Output object of compiler) The following codes are output in the function. movw xch sub xch subc movw ax,_hsmm0 a,x a,_hsmm1 a,x a,_hsmm1+1 _hsmm0,ax
COMPATIBILITY * Modifications are not needed if the other compiler does not use the keyword sreg/_ _sreg. To change to sreg variables, modifications are made according to the method shown above. * Modifications are made by #define. For details, refer to 11.6 Modifications of C Source. These modifications allow sreg variables to be handled as ordinary variables.
318
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Usage of saddr Area
-RD
(2) Usage with saddr automatic allocation option of external variables/external static variables FUNCTION * External variables/external static variables (except const type) are automatically allocated to the saddr area regardless of whether an sreg declaration is made or not. * Depending on the value of n, the external variables and external static variables to be allocated can be specified as follows. Table 11-8. Variables Allocated to saddr Area by -RD Option
Value of n 1 2 Variables Allocated to saddr Area Variables of char and unsigned char types Variables for when n = 1, plus variables of short, unsigned short, int, unsigned int, enum, and pointer type Variables for when n = 2, plus variables of long, unsigned long, float, double, and long double type All variables (including the structures, unions, and arrays in this case only)
4
When omitted
* Variables declared with the keyword sreg are allocated to the saddr area, regardless of the above specification. * The above rule also applies to variables referenced by the extern declaration, and processing is performed as if these variables were allocated to the saddr area. * The variables allocated to the saddr area by this option are treated in the same manner as sreg variables. The functions and restrictions of these variables are as described in (1). METHOD OF SPECIFICATION Specify the -RD [n] (n: 1, 2, or 4) option. RESTRICTIONS * In the -RD [n] option, modules specifying a different n value cannot be linked to each other.
User's Manual U14872EJ1V0UM
319
CHAPTER 11
EXTENDED FUNCTIONS
Usage of saddr Area
-RS
(3) Usage with saddr automatic allocation option of internal static variables FUNCTION * Automatically allocates internal static variables (except const type) to saddr area regardless of whether or sreg declaration is made or not. * Depending on the value of n, the internal static variables to be allocated can be specified as follows. Table 11-9. Variables Allocated to saddr Area by -RS Option
Value of n 1 2 Variables Allocated to saddr Area Variables of char and unsigned char types Variables for when n = 1, plus variables of short, unsigned short, int, unsigned int, enum, and pointer type Variables if n is 2 and variables of long, unsigned long, float, double, and long double type All variables (including the structures, unions, and arrays in this case only)
4
When omitted
* Variables declared with the keyword sreg are allocated to the saddr area regardless of the above specification. * The variables allocated to the saddr area by this option are handled in the same manner as sreg variables. The functions and restrictions for these variables are as described in (1). METHOD OF SPECIFICATION Specify the -RS [n] (n: 1, 2, or 4) option. Remark In the -RS [n] option, modules specifying a different n value can be linked to each other.
320
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Usage of saddr Area
-RK
(4) Usage with saddr automatic allocation option for arguments/automatic variables FUNCTION * Arguments and automatic variables (except const type) are automatically allocated to the saddr area regardless of whether an sreg declaration is made or not. * The arguments and automatic variables to be allocated are specified using the values of n. Table 11-10. Variables Allocated to saddr Area by -RK Option
Value of n 1 2 Variables Allocated to saddr Area Variables of char and unsigned char types Variables for when n = 1, plus variables of short, unsigned short, int, unsigned int, enum, and pointer type Variables for when n = 2, plus variables of long, unsigned long, float, double, and long double type All variables (including the structures, unions, and arrays in this case only)
4
When omitted
* Variables declared with sreg are allocated to the saddr area regardless of the above specifications. * Variables allocated to the saddr area by this option are handled in the same way as sreg variables. * Modules that have different n values specified in the -RK [n] option can be linked. USAGE * Specify the -RK [n] option (where n is 1, 2, or 4). RESTRICTIONS * Only the static model is supported. When the -SM option is not specified, a warning message is output and the automatic allocation is ignored. * Arguments/variables that have been declared register variables are not allocated to the saddr area. * When the -QV option is specified simultaneously, allocation to register DE has priority.
User's Manual U14872EJ1V0UM
321
CHAPTER 11
EXTENDED FUNCTIONS
Usage of saddr Area
-RK
EXAMPLE (C source) sub(int hsmarg) { int hsmauto; hsmauto = hsmarg; }
(Output object of compiler) @@DATS DSEG ?L0003: DS ?L0004: DS @@CODE CSEG _sub: movw movw ret ?L0003, ax ?L0004, ax ; hsmauto SADDRP (2) (2)
322
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(4) How to use the sfr area
Usage of sfr Area
sfr
FUNCTION * The sfr area refers to a group of special function registers such as mode registers and control registers for the various peripherals of the 78K/0S Series microcontrollers. * By declaring the use of sfr names, manipulations on the sfr area can be described at the C source level. * sfr variables are external variables without initial values (undefined). * A write check will be performed on read-only sfr variables. * A read check will be performed on write-only sfr variables. * Assignment of illegal data to an sfr variable will result in a compile error. * The sfr names that can be used are those allocated to an area consisting of addresses FF00H to FFFFH. EFFECT * Manipulations to the sfr area can be described at the C source level. * Instructions to the sfr area are shorter in code length than those to memory. This helps shorten object code and also improves program execution speed. USAGE * Declare the use of an sfr name in the C source with the #pragma preprocessing directive, as follows (the keyword sfr can be described in uppercase or lowercase letters.): #pragma sfr
* The #pragma sfr directive must be described at the beginning of the C source line. (processor type) is specified, however, describe #pragma sfr after that. The following statement and directives may precede the #pragma sfr directive: * Comment statement * Preprocessing directives that do not define or refer to a variable or function
If #pragma PC
* In the C source program, describe an sfr name that the device has as is (without change). In this case, the sfr need not be declared.
User's Manual U14872EJ1V0UM
323
CHAPTER 11
EXTENDED FUNCTIONS
Usage of sfr Area
sfr
RESTRICTIONS * All sfr names must be described in uppercase letters. Lowercase letters are treated as ordinary variables. EXAMPLE (C source) #ifdef _ _K0S_ _ #pragma sfr #endif void main() { P0 -= RXB00; /* RXB00 = 10; } (Output object of compiler) Codes that relate to declarations are not output and the following codes are output in the middle of the function. mov sub mov a, P0 a, RXB00 P0, a ==> error */
324
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Usage of sfr Area
sfr
COMPATIBILITY * Those portions of the C source program not dependent on the device or compiler need not be modified. * Delete the #pragma sfr statement or sort by #ifdef and add the declaration of the variable that was formerly an sfr variable. An example is shown below. #ifdef _ _K0S_ _ #pragma sfr #else /* Declaration of variables */ unsigned char P0; #endif void main(void) { P0 = 0; }
* For devices with the sfr or its alternative functions, a dedicated library must be created to access that area.
User's Manual U14872EJ1V0UM
325
CHAPTER 11
EXTENDED FUNCTIONS
(5) noauto function
noauto Function
noauto
FUNCTION * The noauto function sets restrictions for automatic variables not to output the codes of preprocessing/ postprocessing (generation of stack frame). * All the arguments are allocated to registers or the saddr area (FEE4H to FEE7H) for register variables. If there is an argument that cannot be allocated to registers, a compile error occurs. * Automatic variables can be used only if all the automatic variables are allocated to the registers or saddr area for register variable-use left over after argument allocation. * The noauto function allocates arguments to the saddr area for register variable-use, but only if the -QR option has been specified during compilation. * The noauto function stores arguments other than arguments allocated to the registers in the saddr area for register variable-use, and stores the arguments' descriptions in ascending sequence (refer to APPENDIX A LIST OF LABELS FOR saddr AREA). * The code output when calling the noauto function is the same code as the code for calling a normal function. * When the -SM option is specified, a warning message is only output to the line in which noauto is described first, and all the noauto functions are handled as normal functions. EFFECT * The object code can be shortened and execution speed can be improved. USAGE Declare a function with the noauto attribute in the function declaration, as follows. noauto type-name function-name
326
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
noauto Function
noauto
RESTRICTIONS * When the -ZA option is specified, the noauto function is disabled. * The arguments and automatic variables of the noauto function have restrictions for their types and numbers. The following shows the types of arguments that can be used inside a noauto function. Arguments other than long/signed long/unsigned long, float/double/long double are allocated to register HL. * * * * * * Pointer char/signed char/unsigned char int/signed int/unsigned int short/signed short/unsigned short long/signed long/unsigned long float/double/long double
* The number of arguments and automatic variables that can be used is a maximum of 6 bytes in total size. * These restrictions are checked at compilation. * If arguments are declared with a register, the register declaration is ignored. EXAMPLE (C source) When the -QR option is specified noauto short nfunc(short a, short b, short c); short l, m; void main() { static short ii, jj, kk; l = nfunc(ii, jj, kk); } noauto short nfunc(short a, short b, short c) { m = a + b + c; return(m); }
User's Manual U14872EJ1V0UM
327
CHAPTER 11
EXTENDED FUNCTIONS
noauto Function
noauto
(Output object of compiler) @@CODE CSEG _main: ;line 5: ;line 6: mov xch mov push mov xch mov push mov xch mov call pop pop movw mov xch mov ;line 7: ret ;line 8: ;line 9: _nfunc: push xch xch xch xch push movw push movw movw mov xch mov movw mov xch mov movw
static short ii, jj, kk; l = nfunc(ii, jj, kk); a, !?L0005 a, x a, !?L0005+1 ax a, !?L0004 a, x a, !?L0004+1 ax a, !?L0003 a, x a, !?L0003+1 !_nfunc ax ax ax, bc !_1+1, a a, x !_l, a }
; kk ; kk ; jj ; jj ; ii ; ii ; Calls nfunc (a, b, c) function
; Assigns the return value to external variable l
noauto short nfunc (short a, short b, short c) { hl a, x a, _@KREG12 a, x a, _@KREG13 ax ax, _@KREG14 ax ax, sp hl, ax a,[hl+10] a, x a,[hl+11] _@KREG14, ax a,[hl+8] a, x a,[hl+9] hl, ax ; Saves HL ; ; Sets argument a to _@KREG12 ; ; ; Saves _@KREG12 ; ; Saves _@KREG14 ; ; ; ; ; ; Sets argument c to _@KREG14 ; ; ; ; Sets argument b to HL
User's Manual U14872EJ1V0UM
328
CHAPTER 11
EXTENDED FUNCTIONS
noauto Function
noauto
(Output object of compiler ...continued) ;line movw xch add xch addc xch add xch addc mov xch mov ;line xch movw ;line pop movw pop movw pop ret 10: m = a + b + c; ax, hl a, x a, _@KREG12 a, x a, _@KREG13 a, x a, _@KREG14 a, x a, _@KREG15 !_m+1, a a, x !_m, a 11: return(m); a, x bc, ax 12: } ax _@KREG14, ax ax _@KREG12, ax hl
; ; ; ; ; ; ; ; ; Adds b(HL) and c(_@KREG14) to a(_@KREG12) ; Assigns the calculation result to external variable m
; Returns the contents of external variable m ; ; Restores _@KREG14 ; ; Restores _@KREG12 ; Restores HL
EXPLANATION * In the above example, the noauto attribute is added at the header part of the C source. noauto is declared and stack frame formation is not performed. COMPATIBILITY * The C source program need not be modified if the keyword noauto is not used. * To change variables to noauto variables, modify the program according to the procedure described in USAGE above. * #define must be used. For details, see 11.6 Modifications of C Source.
User's Manual U14872EJ1V0UM
329
CHAPTER 11
EXTENDED FUNCTIONS
(6) norec function
norec Function
norec
FUNCTION * A function that does not call another function by itself can be changed to a norec function. * With norec functions, code for preprocessing and postprocessing (stack frame formation) is not output. * The arguments of the norec function are allocated to registers and saddr area (FEE8H to FEEFH) for norec function arguments. * If arguments cannot be allocated to registers and saddr area, a compile error occurs. * Arguments are stored either in the register or the saddr area (FEE8H to FEEFH) and the norec function is called. * Automatic variables are allocated to the saddr area (FEF0H to FEF7H) and so are the register variables. * The saddr area is not used for allocation when the -QR option is specified during compilation. * If arguments other than long/float/double/long double types are used, the first argument is stored in register AX, the second in register DE, and the third and successive arguments are stored in the saddr area. Note that the arguments stored in registers AX and DE are one argument each regardless of the type of argument. * The argument stored in register AX is copied to register DE if DE does not have the argument stored at the beginning of the norec function. If there is an argument stored in register DE already, the argument stored in AX is copied to _@RTARG6 and 7. * If automatic variables other than long/float/double/long double types are used, the arguments that are left after allocation are stored in the declared order; DE, _@RTARG6 and 7, and _@NRARG0, 1... If automatic variables long/float/double/long double types are used, the arguments that are left after allocation are stored in the declared order; _@NRARG0, 1... The rest of the arguments are stored in the saddr area in the declared order (refer to APPENDIX A LIST OF LABELS FOR saddr AREA). EFFECT * The object code can be shortened and program execution speed can be improved. USAGE Declare a function with the norec attribute in the function declaration, as follows. norec type-name function-name * _ _ leaf can also be described instead of norec.
330
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
norec Function
norec
RESTRICTIONS * No other function can be called from a norec function. * There are restrictions on the type and number of arguments and automatic variables that can be used in a norec function. * When -ZA is specified, norec is disabled and only _ _leaf is enabled. * When the -SM option is specified, a warning message is only output to the line in which norec is described first, and all the norec functions are handled as normal functions. * The restrictions for arguments and automatic variables are checked at compilation, and an error occurs. * If arguments and automatic variables are declared with a register, the register declaration is ignored. * The following shows the types of arguments and automatic variables that can be used in norec functions. norec functions are allocated to the saddr area consecutively if between char/signed char/unsigned char, however if connected to other types, allocation is performed in two-byte alignment. * * * * * * Pointer char/signed char/unsigned char int/signed int/unsigned int short/signed short/unsigned short long/signed long/unsigned long float/double/long double
(When the -QR option is not specified) * The number of arguments that can be used in a norec function is 2 variables, if other than long/float/double/long double types. Arguments cannot be used for long/float/double/long double types. * Automatic variables can use the area that is the combined total of the number of bytes remaining unused by arguments. If types other than long/float/double/long double are used, automatic variables can use up to 4 bytes. Arguments can not be used for long/float/double/long double types. (When the -QR option is specified) * The number of arguments is 6 variables, if types other than long/float/double/long double are used, and 2 variables if long/float/double/long double types are used. * Automatic variables can use the area that is the combined total of the number of bytes remaining unused by arguments and the number of saddr area bytes. If types other than long/float/double/long double are used, automatic variables can use up to 20 bytes and if long/float/double/long double types are used, automatic variables can use up to 16 bytes. * These restrictions are checked at compilation and an error will occur if not satisfied.
User's Manual U14872EJ1V0UM
331
CHAPTER 11
EXTENDED FUNCTIONS
norec Function
norec
EXAMPLE (C source) norec int rout (int a, int b, int c); int i, j; void main ( ){ int k, l, m; i = l + rout (k, l, m) + ++k ; } norec int rout (int a, int b, int c) { int x, y; return } (x + (a<<2) );
332
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
norec Function
norec
(Output object of compiler) When the -QR option is specified EXTRN EXTRN EXTRN . . . _@NRARG0 . . . de . . . ax call _rout: movw mov xch add xch rolc dbnz xch add xch addc movw ret _@RTARG6, ax ; Receives argument from saddr area c, #02H a, x a, a a, x a, 1 c, $$-5 a, x a, _@NRARG1 a, x a, _@NRARG1+1 bc, ax ; Uses automatic variables of saddr area ; ; Uses automatic variables of saddr area ; k !_rout ; Stores argument in AX ; Calls norec function 1 ; Stores argument to DE m ; Stores argument in saddr area _@NRARG0 _@NRARG1 _@NRARG6 ; References saddr area to be used ; ;
User's Manual U14872EJ1V0UM
333
CHAPTER 11
EXTENDED FUNCTIONS
norec Function
norec
EXPLANATION In the above example, the norec attribute is added in the definition of the rout function as well to indicate that the function is norec. COMPATIBILITY * The C source program need not be modified if the keyword norec is not used. * To change variables to norec variables, modify the program according to the procedure described in USAGE above. * #define must be used. For details, see 11.6 Modifications of C Source.
334
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(7) bit type variables
bit Type Variables boolean Type Variables
bit boolean _ _boolean
FUNCTION * A bit or boolean type variable is handled as 1-bit data and allocated to the saddr area. * These variables can be handled the same as external variables that have no initial value (or have an unknown value). * The C compiler outputs the following bit manipulation instructions for these variables. SET1, CLR1, NOT1, BT, BF instruction
EFFECT * Programming at the assembler source level can be performed in C, and the saddr and sfr areas can be accessed in bit units. USAGE * Declare a bit or boolean type inside a module in which the bit or boolean type variable is to be used, as follows: * _ _boolean can also be described instead of bit. bit variable-name boolean variable-name _ _boolean variable-name
* Declare a bit or boolean type inside a module in which the bit or boolean type variable is to be used, as follows. extern extern extern bit variable-name boolean variable-name _ _boolean variable-name
* char, int, short, and long type sreg variables (except the elements of arrays and members of structures) and 8-bit sfr variables can be automatically used as bit type variables. variable-name. n (where n = 0 to 31)
User's Manual U14872EJ1V0UM
335
CHAPTER 11
EXTENDED FUNCTIONS
bit Type Variables boolean Type Variables
bit boolean _ _boolean
RESTRICTIONS * An operation on two bit or boolean type variables is performed by using the CY (carry) flag. For this reason, the contents of the carry flag between statements are not guaranteed. * Arrays cannot be defined or referenced. * A bit or boolean type variable cannot be used as a member of a structure or union. * This type of variable cannot be used as the argument type of a function. * A bit type variable cannot be used as the type of an automatic variable (other than static model). * With bit type variables only, up to 1472 variables can be used per load module (when saddr area [FE20H to FED7H] is used) (normal model). * With bit type variables only, up to 1664 variables can be used per load module (when saddr area [FE20H to FEEFH] is used) (static model). * The variable cannot be declared with an initial value. * If the variable is described along with a const declaration, the const declaration is ignored. * Only operations using 0 and 1 can be performed by the operators and constants shown in Table 11-11. * *, & (pointer reference, address reference), and sizeof operations cannot be performed. * When the -ZA option is specified, only _ _boolean is enabled. Table 11-11. Operators Using Only Constants 0 or 1 (with Bit Type Variable)
Classification Assignment Bitwise AND Bitwise XOR Logical AND Equal = &, &= ^, ^= && == Logical OR Not Equal || != Bitwise OR |, |= Operator Classification Operator
Remark
If sreg variables are used or if -RD, -RS, and -RK (saddr automatic allocation option) options are specified, the number of usable bit type variables decreases.
336
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
bit Type Variables boolean Type Variables
bit boolean _ _boolean
EXAMPLE (C source) #define ON 1 #define OFF 0 extern bit data1; extern bit data2; void main() { data1 = ON; data2 = OFF; while(data1) { data1 = data2; testb(); } if(data1 && data2){ chgb(); } }
(Assembler source) This example is for cases when the user has generated a definition code for a bit type variable. If an extern declaration has not been attached, the compiler outputs the following code. The ORG quasi-directive is not output in this case. PUBLIC PUBLIC @@BITS _data1 _data2 _data1 _data2 BSEG ORG DBIT DBIT 0FE20H ; Allocation to segment ; Declaration
User's Manual U14872EJ1V0UM
337
CHAPTER 11
EXTENDED FUNCTIONS
bit Type Variables boolean Type Variables
bit boolean _ _boolean
(Output object of compiler) The following codes are output in a function. set1 clr1 bf bf bf _data1 _data2 _data1, $?L0001 _data1, $?L0005 _data2, $?L0005 ; Initialized ; Initialized ; Judgment ; Logical AND expression ; Logical AND expression
COMPATIBILITY * The C source program need not be modified if the keyword bit, boolean, or _ _boolean is not used. * To change variables to bit or boolean type variables, modify the program according to the procedure described in USAGE above. * #define must be used. For details, see 11.6 Modifications of C Source (as a result of this, the bit or boolean type variables are handled as ordinary variables.).
338
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(8) ASM statements
ASM Statements
#asm, #endasm _ _asm
FUNCTION (a) #asm - #endasm * The assembler source program described by the user can be embedded in an assembler source file to be output by this C compiler by using the preprocessing directives #asm and #endasm. * #asm and #endasm lines will not be output. (b) _ _asm * An assembly instruction is output by describing an assembly code to a character string literal and is inserted in an assembler source. EFFECT * The global variables of the C source can be manipulated in the assembler source * Functions that cannot be described in the C source can be implemented * The assembler source output by the C compiler can be hand-optimized and embedded in the C source (to obtain efficient objects) USAGE (a) #asm - #endasm * Indicate the start of the assembler source with the #asm directive and the end of the assembler source with the #endasm directive. Describe the assembler source between #asm and #endasm. #asm . . . #endasm (b) _ _asm * Use of _ _asm is declared by the #pragma asm specification made at the beginning of the module in which the ASM statement is to be described (uppercase letters and lowercase letters are distinguished for the keywords following #pragma). * The following items can be described before #pragma asm. * Comments * Other #pragma directives * Preprocessing directives that neither define nor reference variables or functions * The ASM statement is described in the following format in the C source. _ _asm (string literal); /*assembler source*/
* The description method of a character string literal conforms to ANSI, and a line can be continued by using an escape character string (\n: line feed, \t: tab) or , or character strings can be linked.
User's Manual U14872EJ1V0UM
339
CHAPTER 11
EXTENDED FUNCTIONS
ASM Statements
#asm, #endasm _ _asm
RESTRICTIONS * Nesting of #asm directives is not allowed. * If ASM statements are used, no object module file will be created. Instead, an assembler source file will be created. * Only lowercase letters can be described for _ _asm. If _ _asm is described with uppercase and lowercase characters mixed, it is regarded as a user function. * When the -ZA option is specified, only _ _asm is enabled. * #asm - #endasm and _ _asm can only be described inside a function of the C source. Therefore, the assembler source is output to CSEG with the segment name @@CODE. EXAMPLE (a) #asm - #endasm (C source) void main ( ){ callt [init] #endasm }
#asm
(Output object of compiler) The assembler source written by the user is output to the assembler source file. @@CODE _main: callt ret END [init] CSEG
EXPLANATION * In the above example, statements between #asm and #endasm will be output as an assembler source program to the assembler source file.
340
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
ASM Statements
#asm, #endasm _ _asm
(b) _ _asm (C source) #pragma asm int void a, b; ){ _ _ asm("\tmovw ax, _ _ asm("\tmovw } _b, _a\t;ax main (
(Assembler source) @@CODE CSEG _main: movw movw ret END ax, _b, _a ax ;ax ;b <COMPATIBILITY * With a C compiler that supports #asm, modify the program according to the format specified by the C compiler. * If the target device is different, modify the assembler source part of the program.
User's Manual U14872EJ1V0UM
341
CHAPTER 11
EXTENDED FUNCTIONS
(9) Interrupt functions
Interrupt Functions
#pragma vect #pragma interrupt
FUNCTION * The address of a described function name is registered to an interrupt vector table corresponding to a specified interrupt request name. * An interrupt function outputs a code to save or restore the following data (except that used in the ASM statement) to or from the stack at the beginning and end of the function: (1) (2) (3) (4) Registers saddr area for register variables saddr area for arguments/auto variables of norec function (regardless of whether the arguments or variables are used) saddr area for runtime library (normal model only)
Note, however, that depending on the specification or status of the interrupt function, saving/restoring is performed differently, as follows. * If "no change" is specified, codes that save/restore register contents, and that save/restore the contents of the saddr area are not output regardless of whether the codes are used or not. * If "no change" is not specified and if a function is called in the interrupt function, however, the entire register area is saved or restored, regardless of whether use of registers is specified or not. (Normal model) * If the -QR option is not specified at compilation, the saddr area for register variables and the saddr area for the arguments/auto variables of the norec function is not used; therefore, the save/restore code is not output. If the size of the save code is smaller than that of the restore code, the restore code is output. * Table 11-12 summarizes the above and shows the save/restore area.
342
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Interrupt Functions
#pragma vect #pragma interrupt
Table 11-12. Save/Restore Area When Interrupt Function Is Used
Function Called Save/Restore Area Register used All registers saddr area for runtime library used saddr area for all runtime libraries saddr area for register variable used All saddr area for arguments/auto variables of norec function NO BANK Without -QR x x x x x x x x x x With -QR x x Without -QR x x x x With -QR x x x Function Not Called
: Saved x : Not saved (Static model) * Since the saddr area for register variables, the saddr area for automatic variables or norec function arguments, and the saddr area for the runtime library is not used when the -SM option is specified during compilation, only the save and restore code for registers is output; not the code for saddr area. However, when leafwork 1 to 16 has been specified, the code for saving and restoring the byte number to the stack is output from the higher-level address of shared area at the beginning and end of the interrupt function (Refer to 11.5 (23) Static model when the -ZM option is not specified, and 11.5 (32) Static model expansion specification when the -ZM option is specified). Caution If there is an ASM statement in an interrupt function, and if the area reserved for registers of the compiler is used in that ASM statement, the area must be saved by the user.
User's Manual U14872EJ1V0UM
343
CHAPTER 11
EXTENDED FUNCTIONS
Interrupt Functions
#pragma vect #pragma interrupt
EFFECT * Interrupt functions can be described at the C source level. * It is not necessary to be aware of the addresses of the vector table to recognize an interrupt request name. USAGE * Specify an interrupt request name, a function name, stack switching, registers, and whether the saddr area is saved/restored, with the #pragma directive. Describe the #pragma directive at the beginning of the C source (for the interrupt request names, refer to the user's manual of the target device used). * When describing #pragma PC (processor type), describe this #pragma directive after that. The following items can be described before this #pragma directive. * Comment statements * Preprocessing directives that neither define nor reference variables or functions #pragmavect (or interrupt)interrupt request namefunction name [stack change specification] stack use specification No change specification Shared area save/restore specification Save/restore target
344
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Interrupt Functions
#pragma vect #pragma interrupt
Interrupt request name: Function name: Stack change specification:
Described in uppercase letters. Refer to the user's manual of the target device used (example: NMI, INTP0, etc.). Name of the function that describes interrupt processing SP = array name [+ offset location] (example: SP = buff + 10) Define the array by unsigned char (example: unsigned char buff [10];).
Stack use specification: No change specification: Shared area save/restore specification: Save/restore target:
STACK (default) NOBANK leafwork 1 to 16 (when -SM option specified) SAVE_R Save/restore target limited to registers SAVE_RN Save/restore target limited to registers and _@NRATxx (when -SM, -ZM option specified)
: RESTRICTIONS
Space
* Register bank specification is not supported. * An interrupt request name must be described in uppercase letters. * A duplication check on interrupt request names will be made within only one module. * If the same or another interrupt occurs due to the contents of the priority specification flag register and interrupt mask flag register while a vectored interrupt is processed, the contents of the registers may be changed if no change is specified, resulting in an error. The compiler, however, cannot check this error. * callt/noauto/norec/_ _callt/_ _leaf/_ _pascal cannot be specified as the interrupt functions. * An interrupt function is specified with void type (example: void func (void);) because it cannot have an argument or a return value. * Even if an ASM statement exists in the interrupt function, codes saving all the registers and variable areas are not output. If an area reserved for the compiler is used in the ASM statement in the interrupt function, therefore, or if a function is called in the ASM statement, the user must save the registers and variable areas. * If a function specifying no change, register bank, or stack change as the saving destination in #pragma vect/#pragma interrupt specification is not defined in the same module, a warning message is output and the stack change is ignored. In this case, the default stack is used.
User's Manual U14872EJ1V0UM
345
CHAPTER 11
EXTENDED FUNCTIONS
Interrupt Functions
#pragma vect #pragma interrupt
* When stack change is specified, the stack pointer is changed to the location where the offset is added to the array name symbol. The area of the array name is not secured by the #pragma directive. It needs to be defined separately as a global unsigned char type array. * The code that changes the stack pointer is generated at the start of a function, and the code that sets the stack pointer back is generated at the end of a function. * When keywords sreg/_ _sreg are added to the array for stack change, it is assumed that two or more variables with the different attributes and the same name are defined, and a compile error occurs. It is possible to allocate an array in saddr area by the -RD option, but code and speed efficiency will not be improved because the array is used as a stack. It is recommended to use the saddr area for purposes other than a stack. * The stack change cannot be specified simultaneously with the no change. If specified so, an error occurs. * The stack change must be described before the stack use specification. If the stack change is described after the stack use specification, an error occurs. * If leafwork 1 to 16 is specified when the -SM option is not specified, a warning is output and the save/restore specification of the shared area is ignored. EXAMPLE (C source) When there is a shared area (static model only) #pragma interrupt INTP0 inter leafwork4 void func(); void inter() { func(); }
346
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Interrupt Functions
#pragma vect #pragma interrupt
(Compiler output object) EXTRN EXTRN @@CODE CSEG _inter: push push push movw push movw push call pop movw pop movw pop pop pop reti @@VECT06 _@vect06: DW _@KREG12 _@KREG14
ax bc hl ax, _@KREG12 ax ax, _@KREG14 ax !_func ax _@KREG14, ax ax _@KREG12, ax hl bc ax
; Saves the register ; Saves the register ; Saves the register ; Saves the shared area ; Saves the shared area ; Saves the shared area ; Saves the shared area ; Restores the shared area ; Restores the shared area ; Restores the shared area ; Restores the shared area ; Restores registers ; Restores registers ; Restores registers
CSEG _inter
AT
0006H
User's Manual U14872EJ1V0UM
347
CHAPTER 11
EXTENDED FUNCTIONS
Interrupt Functions
#pragma vect #pragma interrupt
COMPATIBILITY * The C source program need not be modified if interrupt functions are not used at all. * To change an ordinary function to an interrupt function, modify the program according to the procedure described in USAGE above. * An interrupt function can be used as an ordinary function by deleting its specification with the #pragma vect or #pragma interrupt directive. * When an ordinary function is to be used as an interrupt function, change the program according to the specifications of each compiler.
348
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(10) Interrupt function qualifier (_ _interrupt)
Interrupt Function Qualifier
_ _interrupt
FUNCTION * A function declared with the _ _interrupt qualifier is regarded as a hardware interrupt function, and execution is returned by the return RETI instruction for the non-maskable/maskable interrupt function. * A function declared with this qualifier is regarded as a (non-maskable/maskable) interrupt function, and saves or restores the registers and variable areas (1) and (4) below, which are used as the work area of the compiler, to or from the stack. If a function call is described in this function, however, all the variable areas are saved to the stack. (1) Registers (2) saddr area for register variables (3) saddr area for arguments/auto variables of norec function (regardless of whether used or not) (4) saddr area for runtime library
Remark
If the -QR option is not specified (default) at compilation, save/restore codes are not output because areas (2) and (3) are not used. If the -SM option is specified at compilation, save/restore codes are not output because areas (2), (3) and (4) are not used.
EFFECT * By declaring a function with this qualifier, the setting of a vector table and interrupt function definition can be described in separate files. USAGE * Describe _ _interrupt as the qualifier of an interrupt function. (For non-maskable/maskable interrupt function) _ _interrupt void func() {processing}
RESTRICTIONS * _ _interrupt_brk is not supported because there is no software interrupt. A warning message is output where _ _interrupt_brk first appeared, the keyword is ignored, and _ _interrupt_brk is handled as a normal function. * The interrupt function cannot specify callt/noauto/norec/_ _callt/_ _leaf/_ _pascal.
User's Manual U14872EJ1V0UM
349
CHAPTER 11
EXTENDED FUNCTIONS
Interrupt Function Qualifier
_ _interrupt
CAUTIONS * The vector address is not set by merely declaring this qualifier. The vector address must be separately set by using the #pragma vect/interrupt directive or assembler description. * The saddr area and registers are saved to the stack. * Even if the vector address is set or the saving destination is changed by #pragma vect (or interrupt) ..., the change in the saving destination is ignored if there is no function definition in the same file, and the default stack is assumed. * To define an interrupt function in the same file as the #pragma vect (or interrupt) ... specification, the function name specified by #pragma vect (or interrupt) ... is judged as the interrupt function, even if this qualifier is not described (for details of #pragma vect/interrupt, refer to USAGE of 11.5 (9) functions). EXAMPLE Declare or define interrupt functions in the following format. The code to set the vector address is generated by #pragma interrupt. #pragma interrupt INTP0 inter _ _interrupt void inter( _ _interrupt void inter( ); ) {processing}; /*prototype declaration*/ /*function body*/ Interrupt
COMPATIBILITY * The C source program need not be modified unless interrupt functions are supported. * Modify the interrupt functions, if necessary, according to the procedure described in USAGE above. * #define must be used to allow the interrupt qualifiers to be handled as ordinary functions. * To use the interrupt qualifiers as interrupt functions, modify the program according to the specifications of each compiler.
350
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(11) Interrupt functions
Interrupt Functions
#pragma DI #pragma EI
FUNCTIONS * The DI and EI codes are output to an object and an object file is created. * If there is no #pragma directive, DI( ) and EI( ) are regarded as ordinary functions. * If "DI( );" is described at the beginning of a function (except the declaration of an automatic variable, comment, and preprocessing directive), the DI code is output before the preprocessing of the function (immediately after the label of the function name). * To output the DI code after the preprocessing of the function, open a new block before describing "DI( );" (delimit this block with `{`). * If "EI( );" is described at the end of a function (except comments and preprocessing directives), the EI code is output after the postprocessing of the function (immediately before the code RET). * To output the EI code before the postprocessing of a function, close a new block after describing "EI( );" (delimit this block with `}'). EFFECT * A function disabling interrupts can be created. USAGE * Describe the #pragma DI and #pragma EI directives at the beginning of the C source. following items may precede the #pragma DI and #pragma EI directives. * * * Comment statements Other #pragma directives Preprocessing directives that neither define nor reference variables or functions However, the
* Describe DI( ); or EI( ); in the source in the same manner as a function call. * DI and EI can be described in either uppercase or lowercase letters after #pragma.
User's Manual U14872EJ1V0UM
351
CHAPTER 11
EXTENDED FUNCTIONS
Interrupt Functions
#pragma DI #pragma EI
RESTRICTIONS * When using these interrupt functions, DI and EI cannot be used as function names. * DI and EI must be described in uppercase letters. If described in lowercase letters, they will be handled as ordinary functions. EXAMPLE #ifdef _ _K0S_ _ #pragma DI #pragma EI #endif
(C source 1) #pragma #pragma void { DI ( ); function body EI ( ); } DI EI )
main (
(Output object of compiler) _main: di preprocessing function body postprocessing ei ret
352
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Interrupt Functions
#pragma DI #pragma EI
(C source 2) #pragma #pragma { { DI ( ); function body EI ( ); } } DI EI )
void main (
(Output object of compiler) _main: preprocessing di function body ei post-processing ret
COMPATIBILITY * The C source program need not be modified if interrupt functions are not used at all. * To change an ordinary function to an interrupt function, modify the program according to the procedure described in USAGE above. * DI and EI can be used as ordinary function names (example: #ifdef_ _K0S_ _ ... #endif) by deleting the #pragma DI and #pragma EI directives or delimiting them with #ifdef. * To use an ordinary function as an interrupt function, modify the program according to the specifications of each compiler.
User's Manual U14872EJ1V0UM
353
CHAPTER 11
EXTENDED FUNCTIONS
(12) CPU control instruction
CPU Control Instruction
#pragma HALT/STOP/NOP
FUNCTION * The following codes are output to the object to create an object file. (1) (2) (3) Instruction for HALT operation (HALT) Instruction for STOP operation (STOP) NOP instruction
EFFECT * The standby function of a microcontroller can be used with a C program. * The clock can be advanced without the CPU operating. USAGE * Describe the #pragma HALT, #pragma STOP, and #pragma NOP instructions at the beginning of the C source. * The following items can be described before the #pragma directive. * Comment statements * Other #pragma directives * Preprocessing directives that neither define nor reference variables or functions * The keywords following #pragma can be described in either uppercase or lowercase letters. * Describe as follows in uppercase letters in the C source in the same format as a function call. (1) (2) (3) HALT ( STOP ( NOP ( ); ); );
RESTRICTIONS * When this feature is used, HALT( ), STOP( ), and NOP( ) cannot be used as function names. * Describe HALT, STOP, and NOP in uppercase letters. If they are described in lowercase letters, they are handled as ordinary functions.
354
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
CPU Control Instruction
#pragma HALT/STOP/NOP
EXAMPLE (C source) #pragma HALT #pragma STOP #pragma NOP main ( { HALT ( STOP ( NOP ( } ); ); ); )
(Output object of compiler) @@CODE _main: halt stop nop CSEG
COMPATIBILITY * The C source program need not be modified if the CPU control instructions are not used. * Modify the program according to the procedure described in USAGE above when the CPU control instructions are used. * HALT, STOP, and NOP can be used as function names by deleting the "#pragma HALT", "#pragma STOP", and "#pragma NOP" statements or delimiting them with #ifdef. * To use these instructions as the CPU control instructions, modify the program according to the specifications of each compiler (such as #asm, #endasm, and asm();).
User's Manual U14872EJ1V0UM
355
CHAPTER 11
EXTENDED FUNCTIONS
(13) Absolute address access function
Absolute Address Access Function
#pragma access
FUNCTION * A code to access the ordinary RAM space is output to the object through direct inline expansion, not by function call, and an object file can be created. * If the #pragma directive is not described, a function accessing an absolute address is regarded as an ordinary function. EFFECT * A specific address in the ordinary memory space can be easily accessed through C description. USAGE * Describe the #pragma access directive at the beginning of the C source. * Describe the directive in the source in the same format as a function call. * The following items can be described before #pragma access. * Comment statements * Other #pragma directives * Preprocessing directives that neither define nor reference variables or functions * The keywords following #pragma can be described in either uppercase or lowercase letters. The following four function names are available for absolute address accessing. peekb, peekw, pokeb, pokew
356
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Absolute Address Access Function
#pragma access
[List of functions for absolute address accessing] (a) unsigned char peekb (addr); unsigned int addr; Returns 1-byte contents of address addr. (b) unsigned int peekw (addr); unsigned int addr; Returns 2-byte contents of address addr. (c) void pokeb (addr, data); unsigned int addr; unsigned char data; Writes 1-byte contents of data to the position indicated by address addr. (d) void pokew (addr, data); unsigned int addr; unsigned int data; Writes 2-byte contents of data to the position indicated by address addr. RESTRICTIONS * A function name for absolute address accessing must not be used. * Describe functions for absolute address accessing in lowercase letters. Functions described in uppercase letters are handled as ordinary functions.
User's Manual U14872EJ1V0UM
357
CHAPTER 11
EXTENDED FUNCTIONS
Absolute Address Access Function
#pragma access
EXAMPLE (C source) #pragma char int a; b; ) access
void main ( {
a = peekb (0x1234); a = peekb (0xfe23); b = peekw (0x1256); b = peekw (0xfe68); pokeb (0x1234, 5); pokeb (0xfe23, 5); pokew (0x1256, 7); pokew (0xfe68, 7); }
358
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Absolute Address Access Function
#pragma access
(Output assembler source) . . . mov mov mov mov mov xch mov movw callt movw callt mov mov mov movw mov xch mov movw movw COMPATIBILITY * The source program need not be modified if a function for absolute address accessing is not used. * Modify the program according to the procedure described in USAGE above if a function for absolute address accessing is used. * The function name of absolute address accessing can be used as a function name by deleting the "#pragma access" statement or delimiting it with #ifdef. * To use a function for absolute address accessing, modify the program according to the specifications of each compiler (#asm, #endasm, asm, etc.). . . .
a, !01234H !_a, a a, 0FE23H !_a, a a, !01256H a, x a, !01257H de, #_b [@@deist] ax, 0FE68H [@@deist] a, #05H !01234H, a 0FE23H, #05H ax, #07H !01257H, a a, x !01256H, a ax, #07H 0FE68H, ax
User's Manual U14872EJ1V0UM
359
CHAPTER 11
EXTENDED FUNCTIONS
(14) Bit field declaration
Bit Field Declaration
Bit field declaration
(1) Extension of type specifier FUNCTION * The bit field of unsigned char type is not allocated straddling over a byte boundary. * The bit field of unsigned int type is not allocated straddling over a word boundary, but can be allocated straddling over a byte boundary. * The bit fields of the same type are allocated in the same byte units (or word units). If the types are different, the bit fields are allocated in different byte units (or word units). EFFECT * The memory can be saved, the object code can be shortened, and the execution speed can be improved. USAGE * As a bit field type specifier, unsigned char type can be specified in addition to unsigned int type. Declare as follows. struct tag-name { unsigned char Field name: bit width; unsigned char Field name: bit width; . . . unsigned int }; Field name: bit width;
EXAMPLE struct tagname { unsigned char A: 1; unsigned char B: 1; . . . unsigned int unsigned int . . . C: 2; D: 1;
360
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Bit Field Declaration
Bit field declaration
COMPATIBILITY * The source program need not be modified. * Change the type specifier to use unsigned char as the type specifier. * The source program need not be modified if unsigned char is not used as a type specifier. * Change unsigned char, if it is used as a type specifier, into unsigned int. (2) Allocation direction of bit field FUNCTION * The direction in which a bit field is to be allocated is changed and the bit field is allocated from the MSB side when the -RB option is specified. * If the -RB option is not specified, the bit field is allocated from the LSB side. USAGE * Specify the -RB option at compile time to allocate the bit field from the MSB side. * Do not specify the option to allocate the bit field from the LSB side. EXAMPLE 1 (Bit field declaration) struct t { unsigned char A:1; unsigned char B:1; unsigned char C:1; unsigned char D:1; unsigned char E:1; unsigned char F:1; unsigned char G:1; unsigned char H:1; };
User's Manual U14872EJ1V0UM
361
CHAPTER 11
EXTENDED FUNCTIONS
Bit Field Declaration
Bit field declaration
EXPLANATION Because a through h are 8 bits or less, they are allocated in 1-byte units. Figure 11-1. Bit Allocation by Bit Field Declaration (Example 1) Bit allocation from MSB with -RB option specified MSB A EXAMPLE 2 (Bit field declaration) struct t { char unsigned char unsigned char unsigned char int unsigned char unsigned char unsigned char unsigned int }; a; b:2; c:3; d:4; e; f:5; g:6; h:2; i:2; B C D E F G LSB H MSB H G F E D C B Bit allocation from LSB without -RB option specified LSB A
362
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Bit Field Declaration
Bit field declaration
EXPLANATION Figure 11-2. Bit Allocation by Bit Field Declaration (Example 2) Bit field allocated from the MSB side when the -RB option is specified MSB b c 1 Vacant a 0 LSB MSB Vacant 1 c b a 0 Bit field allocated from the LSB side when the -RB option is not specified LSB
Member a of char type is allocated to the first byte unit. Members b and c are allocated to subsequent byte units, starting from the second byte unit. If a byte unit does not have enough space to hold the type char member, that member will be allocated to the following byte unit. In this case, if there is only space for 3 bits in the second byte unit, and member d has four bits, it will be allocated to the third byte unit. Vacant 3 e 5 f 7 Vacant 9 h g g 6 Vacant 8 d 2 e 4 Vacant Vacant 7 Vacant 9 Vacant Vacant 3 e 5 g g 6 Vacant 8 h Vacant 2 e 4 f d
Since member g is a bit field of type unsigned int, it can be allocated across byte boundaries. Since h is a bit field of type unsigned char, it is not allocated in the same byte unit as the g bit field of type unsigned int, but is allocated in the next byte unit. i Vacant 11 Vacant 10 Vacant 11 Vacant 10 i
Since i is a bit field of type unsigned int, it is allocated in the next word unit.
User's Manual U14872EJ1V0UM
363
CHAPTER 11
EXTENDED FUNCTIONS
Bit Field Declaration
Bit field declaration
When the -RC option is specified (to pack the structure members), the above bit field becomes as follows.
b
c 1 e 3
Vacant
a 0 d 2 e 4 f 6 Vacant 8 g Vacant
Vacant 1 e 3 g
c
b
a 0 Vacant 2 d
g
Vacant 5
f 5 Vacant 7 Vacant 9 h Vacant
e 4 g 6 Vacant 8 i
h
Vacant 7
i
Vacant 9
Remark
The numbers below the allocation diagrams indicate the byte offset values from the beginning of the structure.
364
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Bit Field Declaration
Bit field declaration
EXAMPLE 3 (Bit field declaration) struct t { char unsigned int unsigned int unsigned int unsigned char unsigned char unsigned char unsigned char unsigned int }; a; b:6; c:7; d:4; e:3; f:10; g:2; h:5; i:6;
Figure 11-3. Bit Allocation by Bit Field Declaration (Example 3) Bit field allocated from the MSB side when the -RB option is specified MSB Vacant 1 b 3 c c 2 a 0 Vacant Vacant 3 LSB MSB Vacant 1 c c 2 a 0 b Bit field allocated from the LSB side when the -RB option is not specified LSB
Since b and c are bit fields of type unsigned int, they are allocated from the next word unit. Since d is also a bit field of type unsigned int, it is allocated from the next word unit. d 5 Vacant 7 e 6 Vacant Vacant 4 Vacant Vacant 5 Vacant 7 Vacant 6 Vacant 4 e d
Since e is a bit field of type unsigned char, it is allocated to the next byte unit.
User's Manual U14872EJ1V0UM
365
CHAPTER 11
EXTENDED FUNCTIONS
Bit Field Declaration
Bit field declaration
f 9 h 11 i
f
g 8 i
Vacant
Vacant 9
g
f
f 8
Vacant 10
Vacant 11
i
i 10
h
f and g, and h and i are each allocated to separate word units. When the -RC option is specified (to pack the structure members), the above bit field becomes as follows. MSB c 1 Vacant 3 e 5 f 7 h 9 Remark i i 8 f g 6 Vacant Vacant 9 Vacant d 4 Vacant Vacant 7 i i 8 b 2 Vacant Vacant 5 Vacant a 0 c Vacant 3 e LSB MSB c 1 d Vacant 2 Vacant 4 b a 0 c LSB
g
f
f 6 h
The numbers below the allocation diagrams indicate the byte offset values from the beginning of the structure.
366
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Bit Field Declaration
Bit field declaration
COMPATIBILITY * The source program need not be modified. * The source program must be modified if the -RB option is used and coding is performed taking the bit field allocation sequence into consideration.
User's Manual U14872EJ1V0UM
367
CHAPTER 11
EXTENDED FUNCTIONS
(15) Changing compiler output section name
#pragma section...
#pragma section...
FUNCTION * A compiler output section name is changed and a start address is specified. If the start address is omitted, the default allocation is assumed. For the compiler output section name and default location, refer to APPENDIX B LIST OF SEGMENT NAMES. In addition, the location of sections can be specified by omitting the start address and using the link directive file at the time of link. For the link directives, refer to the RA78K0S Assembler Package User's Manual Operations (U14876E). * To change the section name @@CALT with an AT start address specified, the callt function must be described before or after the other functions in the source file. * If data is described after the #pragma directive is described, that data is located in the data change section. Another change directive is possible, so if data is described after the rechange directive, that data is located in the rechange section. If data defined before a change is redefined after the change, it is located in the rechanged section. Furthermore, this is valid in the same way for static variables (within the function). EFFECT * Changing the compiler output section repeatedly in one file enables location of each section independently, so that data can be located in the desired data units. USAGE * Specify the name of the section to be changed, a new section name, and the start address of the section, by using the #pragma directive as indicated below. Describe this #pragma directive at the beginning of the C source. Describe this #pragma directive after #pragma PC (processor type). The following items can be described before this #pragma directive. * Comment statements * Preprocessing directives that neither define nor reference variables or functions However, all sections in BSEG and DSEG, and the @@CNST section in CSEG can be described anywhere in the C source, and rechange directives can be performed repeatedly. To return to the original section name, describe the compiler output section name in the changed section. Declare as follows at the beginning of the file. #pragma section compiler output section name new section name [AT start address]
* Of the keywords to be described after #pragma, be sure to describe the compiler output section name in uppercase letters. section, AT can be described in either uppercase or lowercase letters, or in a combination of both.
368
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
#pragma section...
#pragma section...
* The format in which the new section name is to be described must conform to the assembler specifications (up to eight letters can be used for a segment name). * Only the hexadecimal numbers of the C language and the hexadecimal numbers of the assembler can be described as the start address. [Hexadecimal numbers of C language] 0xn / 0xn...n 0Xn / 0xn...n (n = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F)
[Hexadecimal numbers of assembler] nH/n...nH nh/n...nh (n = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F)
* The hexadecimal number must start with a numeral. Example: To express a numeric value with a value of 255 as a hexadecimal number, specify zero before F. It is therefore 0FFH. * For sections other than the @@CNST section in CSEG, that is, sections in which functions are located, this #pragma directive cannot be described other than at the beginning of the C source (after the C text is described); otherwise it causes an error. * If this #pragma directive is executed after the C text is described, an assembler source file is created without an object module file being created. * If this #pragma directive is after the C text is described, a file that contains this #pragma directive and that does not have the C text (including external reference declarations for variables and functions) cannot be included. This results in an error (refer to the error description in Example 1). * An #include statement cannot be described in a file that executes this #pragma directive following the C text description. If described, it causes an error. (refer to the following error description in Example 2). * If the #include statement follows the C text, this #pragma directive cannot be described after this description. If described, it causes an error (refer to the following error description in Example 3).
User's Manual U14872EJ1V0UM
369
CHAPTER 11
EXTENDED FUNCTIONS
#pragma section...
#pragma section...
EXAMPLE 1 Section name @@CODE is changed to CC1 and address 2400H is specified as the start address. (C source) #pragma void { Function body } (Output object) CC1 _main: Preprocessing Function body Post-processing ret EXAMPLE 2 The following is a code example in which the main C code is followed by a #pragma directive. The contents are allocated in the section following "//". #pragma section @@DATA ??DATA int a1; sreg int b1; int c1 = 1; const int d1 = 1; #pragma section @@DATS ??DATS int a2; sreg int b2; int c2 = 1; const int d2 = 1; #pragma section @@DATA ??DATA2 // ??DATA is automatically closed and ??DATA2 becomes valid int a3; // ??DATA2 sreg int b3; int c3 = 3; const int d3 = 3; // ??DATS // @@INIT and @@R_INIT // @@CNST // ??DATA // ??DATS // @@INIT and @@R_INIT // @@CNST // ??DATA // @@DATS // @@INIT and @@R_INIT // @@CNST CSEG AT 2400H section @@CODE main() CC1 AT 2400H
370
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
#pragma section...
#pragma section...
(EXAMPLE 2 ...continued) #pragma section @@DATA @@DATA // ??DATA2 is closed and processing returns to the default @@DATA #pragma section @@INIT ??INIT #pragma section @@R_INIT ??R_INIT // ROMization is invalidated unless both names (@@INIT and @@R_INIT) are changed. // This is the user's responsibility. int a4; sreg int b4; int c4 = 1; const int d4 = 1; #pragma section @@INIT @@INIT #pragma section @@R_INIT @@R_INIT // ??INIT and ??R_INIT are closed and processing returns to the default setting #pragma section @@BITS ??BITS _ _boolean e4; #pragma section @@CNST ??CNST char*const p = "Hello"; // p and "Hello" are both ??CNST // ??BITS // ??DATA // ??DATS // ??INIT and ??R_INIT // @@CNST
EXAMPLE 3 #pragma section @@INIT ??INIT1 #pragma section @@R_INIT ??R_INIT1 #pragma section @@DATA ??DATA1 char c1; int i2; #pragma section @@INIT ??INIT2 #pragma section @@R_INIT ??R_INIT2 #pragma section @@DATA ??DATA2 char c1; int i2 = 1; #pragma section @@DATA ??DATA3 #pragma section @@INIT ??INIT3 #pragma section @@R_INIT ??R_INIT3 extern char c1; int i2; #pragma section @@DATA ??DATA4 #pragma section @@INIT ??INIT4 #pragma section @@R_INIT ??R_INIT4 // ??DATA3 // ??INIT3 and ??R_INIT3
User's Manual U14872EJ1V0UM
371
CHAPTER 11
EXTENDED FUNCTIONS
#pragma section...
#pragma section...
Restrictions when this #pragma directive has been specified after the main C code are explained in the following coding error examples. CODING ERROR EXAMPLE 1 a1.h #pragma section @@DATA ??DATA1 a2.h extern int func1 (void); #pragma section @@DATA ??DATA2 // File containing the main C code followed by the #pragma // directive a3.h #pragma section @@DATA ??DATA3 a4.h #pragma section @@DATA ??DATA3 extern int func2 (void); a.c #include "a1.h" #include "a2.h" #include "a3.h" // Results in an error. // Because the a2.h file contains the main C code followed by this // #pragma directive, file a3.h, which includes only this #pragma // directive, cannot be included. #include "a4.h" // File that includes the main C code. // File containing only the #pragma section. // File containing only the #pragma section
372
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
#pragma section...
#pragma section...
CODING ERROR EXAMPLE 2 b1.h const int i; b2.h const int j; #include "b1.h" b.c const int k; #pragma section @@DATA ??DATA1 #include "b2.h" // Results in an error // Since an #include statement cannot be coded afterward in file // (b.c) in which the main C code is followed by this #pragma // directive. // This does not result in an error since it is not file (b.c) in which // the main C code is followed by this #pragma directive.
CODING ERROR EXAMPLE 3 c1.h extern int j; #pragma section @@DATA ??DATA1 c2.h extern int k; #pragma section @@DATA ??DATA2 // Results in an error. // This #include statement is specified after the main C code in // c3.h, and the #pragma directive cannot be specified afterward. c3.h #include "c1.h" extern int i; #include "c2.h" #pragma section @@DATA ??DATA3 // Results in an error. // This #include statement is specified after the main C code, and // the #pragma directive cannot be specified afterward. c.c #include "c3.h" #pragma section @@DATA??DATA4 // Results in an error. // This #include statement is specified after the main C code in // c3.h, and the #pragma directive cannot be specified afterward. int i; // This does not result in an error since the #pragma directive is // included and processed before the processing of c3.h.
User's Manual U14872EJ1V0UM
373
CHAPTER 11
EXTENDED FUNCTIONS
#pragma section...
#pragma section...
COMPATIBILITY * The source program need not be modified if the section name change function is not supported. * To change the section name, modify the source program according to the procedure described in USAGE above. * Delete #pragma section ... or delimit it with #ifdef. * To change the section name, modify the program according to the specifications of each compiler. RESTRICTIONS * A section name that indicates a segment for the vector table (e.g., @@VECT02, etc.) must not be changed. * If two or more sections with the same name as the one specifying the AT start address exist in another file, a link error occurs. * When changing compiler output section names @@DATS, @@BITS, and @@INIS, limit the range of the specified address within 0FE20H to 0FED7H. CAUTION * A section is equivalent to a segment of the assembler. * The compiler does not check whether the new section name is duplicated with another symbol. Therefore, the user must check to see whether the section name is not duplicated by assembling the output assemble list. * If a section name (*) related to ROMization is changed by using #pragma section, the startup routine must be changed by the user on his/her own responsibility. (*) ROMization-related section name @@R_INIT, @@R_INIS, @@INIT, @@INIS
The startup routine to be used when a section related to ROMization is changed, and an example of changing the end module are described later.
374
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
#pragma section...
#pragma section...
[Examples of Changing Startup Routine in Connection with Changing Section Name Related to ROMization] Here are examples of changing the startup routine (cstart.asm or cstartn.asm) and end module (rom.asm) in connection with changing a section name related to ROMization. (C source) #pragma section @@R_INIT RTT1 #pragma section @@INIT TT1
If a section name that stores an external variable with an initial value has been changed by describing #pragma section indicated above, the user must add to the startup routine the initial processing of the external variable to be stored to the new section. To the startup routine, therefore, add the declaration of the first label of the new section and the portion that copies the initial value, and add the portion that declares the end label to the end module, as described below. RTT1_S and RTT1_E are the names of the first and end labels of section RTT1, and TT1_S and TT1_E are the names of the first and end labels of section TT1. (Example of changing startup routine cstartx.asm) <1> Add the declaration of the label indicating the end of the section with the changed name . . . EXTRN EXTRN EXTRN _main,_exit,_@STBEG _?R_INIT,_?R_INIS,_?DATA,_?DATS RTT1_E,TT1_E . . . Adds EXTRN declaration of RTT1_E and TT1_E
User's Manual U14872EJ1V0UM
375
CHAPTER 11
EXTENDED FUNCTIONS
#pragma section...
#pragma section...
<2> Add a section to copy the initial values from the RTT1 section with the changed name to the TT1 section. . . . LDATS1: MOVW CMPW BZ MOV MOV INCW BR LDATS2: MOVW MOVW LTT1: MOVW CMPW BZ MOV MOV INCW INCW BR LTT2: ; CALL MOVW CALL BR ; !_main AX,#0 !_exit $$ ; exit(0); ; main(); AX,HL AX,#RTT1_E $LTT2 A,[HL] [DE],A HL DE $LTT1 Adds section to copy the initial values from the RTT1 section to the TT1 section DE,#TT1_S HL,#RTT1_S AX,HL AX,#_?DATS $LDATS2 A,#0 [HL],A HL $LDATS1
376
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
#pragma section...
#pragma section...
<3> Set the label of the start of the section with the changed name. . . . @@R_INIT _@R_INIT: @@R_INIS _@R_INIS: @@INIT _@INIT: @@DATA _@DATA: @@INIS _@INIS: @@DATS _@DATS: RTT1 RTT1_S: TT1 TT1_S: @@CALT @@CNST @@BITS ; END CSEG CSEG BSEG CALLT0 DSEG CSEG DSEG SADDRP ; Indicates the start of the RTT1 section ; Adds the label setting ; Indicates the start of the TT1 section ; Adds the label setting DSEG SADDRP DSEG DSEG CSEG UNITP CSEG
User's Manual U14872EJ1V0UM
377
CHAPTER 11
EXTENDED FUNCTIONS
#pragma section...
#pragma section...
(Example of changing end module rom.asm) (1) Add the declaration of the label indicating the end of the section with the changed name NAME ; PUBLIC PUBLIC PUBLIC ; @@R_INIT _?R_INIT: @@R_INIS _?R_INIS: @@INIT _?INIT: @@DATA _?DATA: @@INIS _?INIS: @@DATS _?DATS . . . DSEG SADDRP DSEG SADDRP DSEG DSEG CSEG UNITP CSEG _?R_INIT,_?R_INIS _?INIT,_?DATA,_?INIS,_?DATS RTT1_E,TT1_E Adds RTT1_E and TT1_E @rom
(2) Setting the label indicating the end . . . RTT1 RTT1_E: TT1 TT1_E: ; END DSEG CSEG ; Adds the label setting indicating the end of the RTT1 section. ; Adds the label setting ; Adds the label setting indicating the end of the TT1 section. ; Adds the label setting
378
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(16) Binary constant
Binary Constant
Binary constant 0bxxx
FUNCTION * Describes binary constants at the location where integer constants can be described. EFFECT * Constants can be described in bit strings without being replaced with an octal or hexadecimal number. Readability is also improved. USAGE * Describe binary constants in the C source. The following shows the description method of binary constants. 0b binary number 0B binary number
Remark
Binary number: either `0' or `1'
* A binary constant has 0b or 0B at the start and is followed by the list of numbers 0 or 1. * The value of a binary constant is calculated with 2 as the base. * The type of a binary constant is the first one that can express the value in the following list. * Subscripted binary number: int, unsigned int, long int unsigned long int * Subscripted u or U: * Subscripted l or L: unsigned int, unsigned long int long int unsigned long int * Subscripted u or U and subscripted l or L with: unsigned long int
User's Manual U14872EJ1V0UM
379
CHAPTER 11
EXTENDED FUNCTIONS
Binary Constant
Binary constant 0bxxx
EXAMPLE (C source) unsigned i;
i = 0b11100101; Output object of compiler is the same as the following case. unsigned i; i = 0xE5;
COMPATIBILITY * Modifications are not needed. * Modifications are needed to meet the specifications of the compiler if the compiler supports binary constants. * Modifications into other integer formats such as octal, decimal, and hexadecimal are needed if the compiler does not support binary constants.
380
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(17) Module name changing function
Module Name Changing Function
#pragma name
FUNCTION * Outputs the first eight letters of the specified module name to the symbol information table in a object module file. * Outputs the first eight letters of the specified module name to the assemble list file as symbol information (MOD_NAM) when -G2 is specified and as the NAME quasi directive when -NG is specified. * If a module name with nine or more letters is specified, a warning message is output. * If unauthorized letters are described, an error occurs and the processing is aborted. * If more than one of this #pragma directive exists, a warning message is output, and whichever directive is described later is enabled. EFFECT * The module name of an object can be changed to any name. USAGE * The following shows the description method. #pragma name module name
A module name must consist of the characters that the OS authorizes as a file name except `(` `)'. Upper case and lowercase letters are distinguished. EXAMPLE #pragma name module1 . . .
COMPATIBILITY * Modifications are not needed if the compiler does not support the module name changing function. * To change a module name, modifiy according to USAGE above. * Delete #pragma name . . . or delimit it with #ifdef. * To change a module name, modify the program according to the specifications of each compiler.
User's Manual U14872EJ1V0UM
381
CHAPTER 11
EXTENDED FUNCTIONS
(18) Rotate function
Rotate Function
#pragma rot
FUNCTION * Outputs the code that rotates the value of an expression to the object with direct inline expansion instead of function call and generates an object file. * If there is no #pragma directive, the rotate function is regarded as an ordinary function. EFFECT * The rotate function can be realized by the C source or ASM description even if the processing to perform rotate is not described. USAGE * Describe in the source in the same format as the function call. available for the rotate function. rorb, rolb, rorw, rolw The following four function names are
[List of functions for rotate] (a) unsigned char rorb (x, y) ; unsigned char x ; unsigned char y ; Rotates x to the right y times. (b) unsigned char rolb (x, y) ; unsigned char x ; unsigned char y ; Rotates x to the left y times. (c) unsigned int rorw (x, y) ; unsigned int x ; unsigned char y ; Rotates x to the right y times. (d) unsigned int rolw (x, y) unsigned int x ; unsigned char y ; Rotates x to the left y times. Caution The above-mentioned function declaration is not affected by the -ZI option.
User's Manual U14872EJ1V0UM
382
CHAPTER 11
EXTENDED FUNCTIONS
Rotate Function
#pragma rot
* Declare the use of the function for rotate by the #pragma rot directive of the module. However, the following items can be described before #pragma rot. * Comments * Other #pragma directives * Preprocessing directives that neither define nor reference variables or functions * Keywords following #pragma can be described in either uppercase or lowercase letters. EXAMPLE (C source) #pragma rot unsigned char a = 0x11 ; unsigned char b = 2 ; unsigned char c ; void main ( ) { c = rorb(a, b) ; }
(Output assembler source) mov mov mov ror dbnz mov a,!_b c,a a,!_a a, 1 c,$$-1 !_c,a
RESTRICTIONS * The function names for rotate cannot be used as function names. * The function names for rotate must be described in lowercase letters. If the functions for rotate are described in uppercase letters, they are handled as ordinary functions.
User's Manual U14872EJ1V0UM
383
CHAPTER 11
EXTENDED FUNCTIONS
Rotate Function
#pragma rot
COMPATIBILITY * Modification is not needed if the compiler does not use the functions for rotate. * To change to functions for rotate, modify according to USAGE above. * Delete the #pragma rot statement or delimit it with #ifdef. * To use as a function for rotate, modify the program according to the specifications of each compiler (#asm, #endasm or asm() ; , etc.).
384
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(19) Multiplication function
Multiplication Function
#pragma mul
FUNCTION * Outputs the code that multiplies the value of an expression to the object with direct inline expansion instead of function call and generates an object file. * If there is no #pragma directive, the multiplication function is regarded as an ordinary function. EFFECT * Codes that are compatible with the CC78K0 and utilize the data size of the multiplication instruction I/O are generated. Therefore, codes with a smaller size than the description of ordinary multiplication expressions can be generated. USAGE * Describe in the same format as that of a function call in the source. mulu
[List of multiplication functions] unsigned int mulu (x, y) ; unsigned char x ; unsigned char y ; Performs unsigned multiplication of x and y. * Declare the use of functions for multiplication by the #pragma mul directive of the module. However, the following items can be described before #pragma mul. * Comments * Other #pragma directives * Preprocessing directives that neither define nor reference variables or functions * Keywords following #pragma can be described in either uppercase or lowercase letters.
User's Manual U14872EJ1V0UM
385
CHAPTER 11
EXTENDED FUNCTIONS
Multiplication Function
#pragma mul
RESTRICTIONS * Multiplication functions are not expanded but are called by the library. EXAMPLE (C source) #pragma mul unsigned char a = 0x11 ; unsigned char b = 2 ; unsigned int i ; void main() { i = mulu(a, b) ; }
(Output object of compiler) mov mov mov movw a,!_b x,a a,!_a de,#_i
callt [@@mulu] callt [@@deist]
COMPATIBILITY * Modifications are not needed if the compiler does not use the functions for multiplication. * To change to functions for multiplication, modify according to USAGE above. * Function names for multiplication can be used as function names by deleting the #pragma mul statement or delimiting it with #ifdef. * To use as functions for multiplication, modify the program according to the specifications of each compiler (#asm, #endasm or asm() ;, etc.).
386
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(20) Division function
Division Function
#pragma div
FUNCTION * Outputs the code which divides the value of an expression from object with direct inline expansion instead of function call and generates an object code file. * If there is no #pragma directive, the function for division is regarded as an ordinary function. EFFECT * Codes that are compatible with the CC78K0 and utilize the data size of the division instruction I/O are generated. Therefore, codes with a faster execution speed and smaller size than the description of ordinary division expressions can be generated. USAGE * Describe in the same format as that of a function call in the source. The following two function names are available for division. divuw, moduw
List of division functions (a) unsigned int divuw(x, y) ; unsigned int x ; unsigned char y ; Performs unsigned division of x and y and returns the quotient. (b) unsigned char moduw(x, y) ; unsigned int x ; unsigned char y ; Performs unsigned division of x and y and returns the remainder. Caution The above-mentioned function declaration is not affected by the -ZI option.
* Declare the use of the functions for division by the #pragma div directive of the module. However, the following items can be described before #pragma div. * Comments * Other #pragma directives * Preprocessing directives that neither define nor reference variables or functions * Keywords following #pragma can be described in either uppercase or lowercase letters.
User's Manual U14872EJ1V0UM
387
CHAPTER 11
EXTENDED FUNCTIONS
Division Function
#pragma div
RESTRICTIONS * The division functions are not expanded in line, but are called by the library. EXAMPLE (C source) #pragma div unsigned int a = 0x1234 ; unsigned char b = 0x12 ; unsigned char c ; unsigned int i ; void main () { i = divuw(a, b) ; c = moduw(a, b) ; }
(Output object of compiler) mov mov movw callt callt movw callt mov mov movw callt callt mov mov a,!_b c,a de,#_a [@@deilo] [@@divuw] de,#_i [@@deist] a,!_b c,a de,#_a [@@deilo] [@@divuw] a,c !_c,a
388
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Division Function
#pragma div
COMPATIBILITY * Modification is not needed if the compiler does not use the functions for division. * To change to functions for division, modify according to USAGE above. * The function names for division can be used as function names by deleting the #pragma div statement or delimiting it with #ifdef. * To use as a function for division, modify the program according to the specifications of each compiler (#asm, #endasm or asm() ; , etc.).
User's Manual U14872EJ1V0UM
389
CHAPTER 11
EXTENDED FUNCTIONS
(21) BCD operation function
BCD Operation Function
#pragma bcd
FUNCTION * Outputs the code that performs a BCD operation on the expression value in an object by direct inline expansion rather than by function call, and generates an object file. * If there is no #pragma directive, the function for BCD operation is regarded as an ordinary function. EFFECT * Even if the process of the BCD operation is not described, the BCD operation function can be realized by the C source or ASM statements. USAGE * The same format as that of a function call is coded in the source. There are 13 types of function names for BCD operation, as listed below. Refer to List of functions for BCD operation, later in this chapter for more information. adbcdb, sbbcdb, adbcdbe, sbbcdbe, adbcdw, sbbcdw, adbcdwe, sbbcdwe, bcdtob, btobcde, bcdtow, wtobcd, btobcd
* Use of functions for division is declared by the module's #pragma bcd directive. However, the following items can be coded before #pragma bcd. * Comments * Other #pragma directives * Preprocessing directives that neither define nor reference variables or functions * Either uppercase or lowercase letters can be used for keywords described after #pragma. RESTRICTIONS * BCD operation function names cannot be used as function names. * The BCD operation function is coded in lowercase letters. If uppercase letters are used, these functions are regarded as an ordinary functions. * adbcdwe and sbbcdwe are not supported in the static model.
390
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
BCD Operation Function
#pragma bcd
EXAMPLE (C source) #pragma bcd unsigned char a = 0x12 ; unsigned char b = 0x34 ; unsigned char c ; void main ( ) { c = adbcdb (a, b) ; c = sbbcdb (b, a) ; }
(Output assembler source) mov add adjba mov mov sub adjbs mov !_c, a !_c, a a, !_b a, !_a a, !_a a, !_b
[List of functions for BCD operation] (1) unsigned char adbcdb (x, y) ; unsigned char x ; unsigned char y ; Decimal addition is carried out by the BCD adjustment instruction. (2) unsigned char sbbcdb (x, y) ; unsigned char x ; unsigned char y ; Decimal subtraction is carried out by the BCD adjustment instruction.
User's Manual U14872EJ1V0UM
391
CHAPTER 11
EXTENDED FUNCTIONS
BCD Operation Function
#pragma bcd
(3) unsigned int adbcdbe (x, y) ; unsigned char x ; unsigned char y ; Decimal addition is carried out by the BCD adjustment instruction (with result expansion). (4) unsigned int sbbcdbe (x, y) ; unsigned char x ; unsigned char y ; Decimal subtraction is carried out by the BCD adjustment instruction (with result expansion). If a borrow occurs, the higher digits are set to 0x99. (5) unsigned int adbcdw (x, y) ; unsigned int x ; unsigned int y ; Decimal addition is carried out by the BCD adjustment instruction. (6) unsigned int sbbcdw (x, y) ; unsigned int x ; unsigned int y ; Decimal subtraction is carried out by the BCD adjustment instruction. (7) unsigned long adbcdwe (x, y) ; unsigned int x ; unsigned int y ; Decimal addition is carried out by the BCD adjustment instruction (with result expansion). (8) unsigned long sbbcdwe (x, y) ; unsigned int x ; unsigned int y ; Decimal subtraction is carried out by the BCD adjustment instruction (with result expansion). If a borrow occurs, the higher digits are set to 0x9999. (9) unsigned char bcdtob (x) . unsigned char x ; Decimal numbers are converted to binary numbers. (10) unsigned int btobcde (x) ; unsigned char x ; Binary numbers are converted to decimal numbers.
392
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
BCD Operation Function
#pragma bcd
(11) unsigned int bcdtow (x) ; unsigned int x ; Decimal numbers are converted to binary numbers. (12) unsigned int wtobcd (x) ; unsigned int x ; Decimal numbers are converted to binary numbers. However, if the value of x exceeds 10000, 0xffff is returned. (13) unsigned char btobcd (x) ; unsigned char x ; Decimal numbers are converted to binary numbers. However, the overflow is discarded. Caution The above-mentioned function declarations are not influenced by the -ZI and -ZL options. COMPATIBILITY * Modification is not needed if functions for BCD operations are not used. * To change another function to the function for BCD operation, modify according to USAGE above. * A BCD operation function name can be used as a function name by deleting the #pragma bcd statement or delimiting it with #ifdef. * To use pragma bcd as a BCD operation function, modify the program according to the specifications of each compiler (#asm, #endasm or asm(); etc.).
User's Manual U14872EJ1V0UM
393
CHAPTER 11
EXTENDED FUNCTIONS
(22) Data insertion function
Data Insertion Function
#pragma opc
FUNCTION * Inserts constant data into the current address. * When there is no #pragma directive, the function for data insertion is regarded as an ordinary function. EFFECT * Specific data and instructions can be embedded in the code area without using the ASM statement. When ASM is used, an object cannot be obtained without going through the assembler, whereas if the data insertion function is used, an object can be obtained without going through the assembler. USAGE * Describe using uppercase letters in the source in the same format as that of a function call. * The function name for data insertion is _ _OPC. [List of data insertion functions] void _ _OPC (unsigned char x,...); Insert the value of the constant described in the argument to the current address. Arguments can describe only constants. * Declare the use of functions for data insertion by the #pragma opc directive. However, the following items can be described before #pragma opc. * Comments * Other #pragma directives * Preprocessing directives that neither define nor reference variables or functions * Keywords following #pragma can be described in either uppercase or lowercase letters. RESTRICTIONS * The function names for data insertion cannot be used as function names (when #opc is specified). * _ _OPC must be described in uppercase letters. If it is described in lowercase letters, it is handled as an ordinary function.
394
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Data Insertion Function
#pragma opc
EXAMPLE (C source) #pragma opc void main ( ) { _ _OPC(0xBF) ; _ _OPC(0xA1, 0x12) ; _ _OPC(0x10, 0x34, 0x12) ; }
(Output object of compiler) _main : ; line DB ; line DB DB ; line DB DB DB ; line ret 4 : _ _OPC (0xBF) ; 0BFH 5 : _ _OPC (0xA1, 0x12) ; 0A1H 012H 6 : _ _OPC (0x10, 0x34, 0x12) ; 010H 034H 012H 7:}
COMPATIBILITY * Modification is not needed if the compiler does not use the functions for data insertion. * To change to functions for data insertion, modify according to USAGE above. * Function names for data insertion can be used as function names by deleting the #pragma opc statement or delimiting it with #ifdef. * To use as a function for data insertion, modify the program according to the specifications of each C compiler (#asm, #endasm or asm() ; , etc.).
User's Manual U14872EJ1V0UM
395
CHAPTER 11
EXTENDED FUNCTIONS
(23) Static model
Static Model
FUNCTION * All arguments are passed through registers (Refer to 11.7.5 Static model function call interface). * Function arguments that are passed through registers are allocated in the function-specific static area. * Automatic variables are allocated to the function-specific static area. * In the case of the leaf function
Note
, arguments and automatic variables are allocated to the saddr area below
0FEFFH, in the order of description starting from the higher addresses. Since the saddr area is commonly used by the leaf functions of all modules, this area is referred to as the shared area. The maximum size of the shared area is defined by the parameter when the -SM option is specified. -SM [nn]: nn = 0 to 16
nn bytes are assigned as shared area and the rest are allocated to the function-specific static area. If nn = 00 is specified or this specification is omitted, the shared area is not used. Note For the functions that do not call functions, it is not necessary to describe norec/_ _leaf since the compiler executes automatic determination. * It is possible to add the sreg/_ _sreg keywords to function arguments and automatic variables. Function arguments and automatic variables that have the sreg/_ _sreg keywords added are allocated to the saddr area. As a result, bit manipulation becomes possible. * By specifying the -RK option, function arguments and automatic variables (except for the static variables in functions) are allocated to saddr and bit manipulation becomes possible (Refer to 11.5 (3) How to use the saddr area). * The compiler executes the following macro definition automatically. #define _ _STATIC_MODEL_ _ 1
EFFECT * Normally, instructions that access the static area are shorter and faster than those that access static frames. Accordingly, it is possible to shorten object codes and increase execution speed. * The save/restore processing of arguments and variables that use the saddr area (register variables in interrupt functions, norec function argument/automatic variables, runtime library arguments) is not performed, as a result, it is possible to increase the speed of interrupt processing. * Memory space can be saved since the data area is commonly used by several leaf functions. USAGE * Specify the -SM option during compilation. The object in this case is called the static model, while the object without specification of the -SM option is called normal model.
396
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Static Model
EXAMPLE An example of the -SM4 specification is as follows. (C source) void sub (char, char, char) ; void main () { char i = 1 ; char j, k ; j=2; k=i+j; sub (i, j, k) ; } void sub (char p1, char p2, char p3) { char a1, a2 ; a1 = 1<(Output object of compiler) @@DATA DSEG (1) (1) (1) (1) ; Automatic variable i of function main ; Automatic variable j of function main ; Automatic variable k of function main ; Automatic variable a2 of function sub
!L0003: DS !L0004: DS !L0005: DS !L0008: DS
; line ; line ; line @@CODE _main: ; line
1: void sub (char, char, char) ; 2: void main () 3: { CSEG 4 : char i = 1 ; mov mov a,#01H !?L0003,a ;1 ;i ; Automatic variable i
; line
5: char j, k ;
User's Manual U14872EJ1V0UM
397
CHAPTER 11
EXTENDED FUNCTIONS
Static Model
(Output object of compiler ...continued) ;line inc mov ; line add mov ; line mov mov movw movw call ; line ret ; line ; line _sub: mov movw mov movw mov ; line ; line mov mov ; line mov add mov ; line ret _@KREG15, a ax, bc _@KREG14, a ax, hl _@KREG13, a 12 : char a1, a2 ; 13 : a1 = p1 ; a,_@KREG15 _@KREG12, a a,_@KREG14 a,_@KREG13 !?L0008, a ;p1 ;a1 ;p2 ;p3 ;a2 ; 1st argument p1 ; Automatic variable a1 is the shared area ; 2nd argument p2 ; Adds 3rd argument p3 ; Automatic variable a2 is in the specific function area ; Allocates the 3rd argument to the shared area ; Allocates the 2nd argument to the shared area ; Allocates the 1st argument to the shared area 10 : void sub (char p1, char p2, char p3) 11 : { 6:j=2; a !?L0004,a a, !?L0003 !?L0005, a 8 : sub (i, j, k) ; hl, ax a, !?L0004 bc, ax a, !?L0003 !_sub ;i ;j ; Passes j through register B ; Passes i through register A ; Passes k through register H ;j ;i ;k ; Automatic variable j ; Add i and j ; Substitute for k
7:k=i+j;
9:}
14 : a2 = p2 + p3 ;
15 : }
398
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Static Model
RESTRICTIONS * Static model modules cannot be linked with a modules of a normal model. However, static model modules can be linked to each other even if the maximum size of the shared area is different. * Floating-point numbers are not supported. If the float and double keywords are described, a fatal error occurs. * Arguments are limited to a maximum of 3 arguments and 6 bytes in total. * It is impossible to use variable length arguments since arguments are not passed through stacks. Using variable length arguments causes an error. * Arguments and return values of structures/unions cannot be used. The description of these arguments and values causes an error. * The noauto/norec/_ _leaf functions cannot be used. A warning message is output and the descriptions are ignored (Refer to 11.5 (5) noauto functions, 11.5 (6) norec functions). * Recursive functions cannot be used. As function arguments and the automatic variable area are statically secured, recursive functions cannot be used. An error is generated for recursive functions that can be detected by the compiler. * A prototype declaration cannot be omitted. An error is generated if neither the function's real definition nor a prototype declaration exist, in spite of there being a function call. * Due to the restrictions of arguments and inability to use recursive functions, some standard libraries cannot be used. * If the -ZL option has not been specified, a warning is output and processing is carried out as if the -ZL option was specified. long types are therefore always regarded as int types (see 11.5 (24) Type modification). COMPATIBILITY * When creating objects of normal model, source modification is not needed unless the -SM option is specified. * To create a static model object, modifications are made according to USAGE above. * Source modification is not needed if re-compiling is performed by another compiler. CAUTIONS * Since arguments/automatic variables are secured statically, the contents of arguments/automatic variables in recursive functions may be destroyed. An error occurs when the function calls itself directly. However, no error occurs when the function calls itself after an other function is called since the compiler cannot detect this processing. * During an interruption, the contents of arguments/automatic variables may be destroyed if the function being processed is called by interrupt servicing (interrupt functions and functions that are called by interrupt functions). * During an interruption, save/restore of the shared area is not executed even when the functions being processed are using the shared area.
User's Manual U14872EJ1V0UM
399
CHAPTER 11
EXTENDED FUNCTIONS
(24) Type modification
Type Modification
-ZI
(1) Change from int/short type to char type FUNCTION * int and short types are regarded as char type. In other words, int and short descriptions become equal to a char description. * Details of the type modification are given as follows (some are affected by the -QU options). Table 11-13. Details of Type Modification (Change from int and short Type to char Type)
Type Described in C Source short, short int, int short, short int, int unsigned short, unsigned short int, unsigned, unsigned int signed short, signed short int, signed, signed int Option With -QU Without -QU - - Type after Modification
unsigned char
signed char unsigned char
signed char
* Outputs warning message to the line where the int or short keywords first appeared in C source. * The -QC option becomes valid regardless of whether it is specified. A warning message is output when there is no -QC option specification, and the -QC option becomes valid. * If the -ZA option is specified at the same time (such as the -ZAI option), a warning message is output (only when -W2 is specified). * The following statements can be described by a type specifier and omitted, so are regarded as char type. * Arguments and returned values of functions * Type specifier omitted variables/function declaration * The compiler executes the following macro definition automatically. #define _ _FROM_INT_TO_CHAR_ _ 1 * Some standard libraries cannot be used. USAGE * The -ZI option is specified. RESTRICTIONS * -ZI specified and -ZI unspecified modules cannot be linked together.
400
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Type Modification
-ZL
(2) Change from long type to int type FUNCTION * long type is regarded as int type. In other words, a long description becomes equal to an int description. * Details of the type modification are given as follows. Table 11-14. Details of Type Modification (Change from long Type to int Type)
Type Described in C Source unsigned long, unsigned long int long, long int, signed long, signed long int unsigned int signed int Type after Modification
* Outputs warning message to the line where the long keyword first appeared in C source. * If the -ZA option is specified at the same time (-ZAL), a warning message is output (only when -W2 is specified). * The compiler executes the following macro definition automatically. #define _ _FROM_LONG_TO_INT_ _ 1 * Some standard libraries cannot be used. USAGE * Specify the -ZL option. RESTRICTIONS * -ZL specified and -ZL unspecified modules cannot be linked together.
User's Manual U14872EJ1V0UM
401
CHAPTER 11
EXTENDED FUNCTIONS
(25) Pascal function
Pascal Function
_ _pascal
FUNCTION * Generates the code that corrects the stack used for placing arguments during the function call on the called function side, not on the side calling the function. EFFECT * Object code can be shortened if function calls appear in many places. USAGE * When a function is declared, add a _ _pascal attribute to the beginning. RESTRICTIONS * The pascal function does not support variable length arguments. If a variable length argument is defined, a warning is output and the _ _pascal keyword is ignored. * The keywords norec/_ _interrupt cannot be specified in a pascal function. If they are specified, in the case of the norec keyword, the _ _pascal keyword is ignored and in the case of the _ _interrupt/_ _interrupt_brk/ _ _rtos_interrupt keywords, an error is output. * If a prototype declaration is incomplete, normal operation may not be possible, so a warning message is output when a pascal function's physical definition or prototype declaration is missing. * Pascal functions are not supported when the static model specification option (-SM) is specified. If -SM is specified when using the pascal function, a warning message is output to the place where the _ _ pascal keyword first appeared, and the _ _ pascal keyword in the input file is ignored. EXPLANATION * The -ZR option enables the change of all functions to the pascal function. However, if the pascal function is used for functions that have few calls, the object code may increase.
402
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Pascal Function
_ _pascal
EXAMPLE (C source) _ _pascal int func(int a, int b, int c); void main() { int ret_val; ret_val = func(5, 10, 15); } _ _pascal int func(int a, int b, int c); { return (a + b + c); }
(Output object of compiler) _main: push movw callt movw push mov push mov call movw mov xch mov pop pop ret hl ax, #02H [_@cprep] ax, #0FH ax x, #0AH ax x, #05H !_func ax, bc [h1+1], a a, x [hl],a ax hl ; ret_val ; The stack is not modified here. ; ret_val ;5 ; 10 ; 15
User's Manual U14872EJ1V0UM
403
CHAPTER 11
EXTENDED FUNCTIONS
Pascal Function
_ _pascal
(Output object of compiler ...continued) _func: push push movw movw mov mov xch mov addc xch add xch addc movw pop pop pop pop pop push hl ax ax, sp hl, ax a, [hl] a, [hl + 6] a, x a, [hl + 1] a, [hl + 7] a, x a, [hl + 8] a, x a, [hl + 9] bc, ax ax hl de ax ax de ; Obtains the return address ; ; Modifies the 4-byte stack consumed by the caller ; Reloads return address ;c ;c ;a ;b ;a ;b
COMPATIBILITY * If the reserved word, _ _ pascal is not used, modification is not required. * To change to the Pascal function, modify according to USAGE above. * Compatibility is maintained by using #define. * By this conversion, the pascal function is regarded as an ordinary function.
404
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(26) Automatic pascal functionization of function call interface
Automatic Pascal Functionization of Function Call Interface
-ZR
FUNCTION * With the exception of norec/_ _interrupt/ variable length argument functions, _ _pascal attributes are added to all functions. USAGE * Specify the -ZR option during compilation. RESTRICTIONS * Modules in which the -ZR option is specified and modules in which the -ZR option is not specified cannot be linked. If a link is executed, it results in a link error. * It is impossible to specify the static model specification option (-SM) and the -ZR option at the same time. If specified, a warning message is output and the -ZR option is ignored. * Since the mathematical function standard library does not support the pascal function, the -ZR option cannot be used when the mathematical function standard library is used. Remark For details of the pascal function call interface, refer to 11.7.6 Pascal function call interface.
User's Manual U14872EJ1V0UM
405
CHAPTER 11
EXTENDED FUNCTIONS
(27) Method of int expansion limitation of argument/return value
Method of int Expansion Limitation of Argument/Return Value
-ZB
FUNCTION * When the type definition of the function return value is char/unsigned char, the int expansion code of the return value is not generated. * When the prototype of the function argument is defined and the argument definition of the prototype is char/unsigned char, the int expansion code of the argument is not generated. EFFECT * The object code can be reduced and the execution speed improved since the int expansion codes are not generated. USAGE * The -ZB option is specified during compilation. EXAMPLE (C source)
unsigned char func1(unsigned char x, unsigned char y); unsigned char c, d, e; void main() { c = func1(d, e); c = func2(d, e); } unsigned char func1(unsigned char x, unsigned char y) { return x + y; }
(Output object of compiler) When -ZB is specified _main: ; line 5: mov xch push mov xch call c = func1 (d, e) ; a, !_e a, x ax a, !_d a, x !_func1 ; int expansion is not executed ; int expansion is not executed
406
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Method of int Expansion Limitation of Argument/Return Value
-ZB
(Output object of compiler) (continued) pop mov mov ; line mov xch xor push mov xch xor call pop mov mov ; line ret ; line ; line _func1: push push movw movw ; line mov add mov ; line pop pop ret END hl ax ax, sp hl, ax a, [hl];x a, [hl+6];y c, a 11: } ax hl 8: 9: unsigned char func1 (unsigned char x, unsigned char y){ ax a, c !_c, a 6: c = func2 (d, e) ; a, !_e a, x a, a ax a, !_d a, x a, a !_func2 ax a, c !_c, a 7: } ; Executes int expansion since there is no prototype declaration ; Executes int expansion since there is no prototype declaration
10: return x+y;
User's Manual U14872EJ1V0UM
407
CHAPTER 11
EXTENDED FUNCTIONS
Method of int Expansion Limitation of Argument/Return Value
-ZB
RESTRICTIONS * If the files are different between the definition of the function body and the prototype declaration to this function, the program may operate incorrectly. COMPATIBILITY * If the prototype declarations for all definitions of function bodies are not correctly performed, perform correct prototype declaration. Alternatively, do not specify the -ZB option. * No modification is needed.
408
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(28) Array offset calculation simplification method
Array Offset Calculation Simplification Method
-QW2, -QW3, -QW4, -QW5
FUNCTION * When calculating the offset of char/unsigned char/unsigned int/short/unsigned short types and the index is an unsigned char-type variable, a code to calculate only lower bytes is generated based on the presumption that there is no carry-over. * When the -QW2 option is specified, a code to calculate only lower bytes for the offset is generated with a speed-based priority only when referencing the sequence of the saddr area configuration with an unsigned char variable. * When the -QW3 option is specified, the code to calculate only lower bytes for the offset is generated with a speed-based priority when referencing the sequence with an unsigned char variable regardless of the configured area. * When the -QW4 option is specified, a code to calculate only lower bytes for the offset is generated with a size-based priority only when referencing the sequence of the saddr area configuration with an unsigned char variable. * When the -QW5 option is specified, a code to calculate only lower bytes for the offset is generated with a size-based priority when referencing the sequence with an unsigned char variable regardless of the configured area. EFFECT * Realizes object code reduction and execution speed improvement since the offset calculation code is simplified. USAGE * Specify the -QW2, -QW3, -QW4, and -QW5 options during compilation. EXAMPLE (C source) unsigned char c ; unsigned char ary [10] ; sreg unsigned char sary [10] ; void main () { unsigned char a ; a = ary [c] ; a = sary [c] ; }
User's Manual U14872EJ1V0UM
409
CHAPTER 11
EXTENDED FUNCTIONS
Array Offset Calculation Simplification Method
-QW2, -QW3, -QW4, -QW5
(Output of compiler object) When -QW3 is specified _main : push push movw movw ; line ; line ; line mov add mov mov mov mov ; line mov add mov mov mov mov ; line pop pop ret 7: 8 : a = ary [c] ; a, !_c a, #low (_ary) e, a d, #high (_ary) a, [de] [hl + 1], a 9 : a = sary [c] ; a, !_c a, #low (_sary) e, a d, #0FEH ; 254 a, [de] [hl + 1], a 10 : } ax hl ;a ; Calculates only lower bytes ;a ; Calculates only lower bytes hl ax ax, sp hl, ax
6 : unsigned char a ;
RESTRICTIONS * If the configuration addresses of the sequence that is the target for offset calculation simplification is over the border of 256 bytes, the program may operate incorrectly. COMPATIBILITY * Assign the layout so that it does not exceed 256 bytes. Alternatively, do not specify the -QW2, -QW3, -QW4 and -QW5 options. * No modification is needed.
410
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(29) Register direct reference function
Register Direct Reference Function
#pragma realregister
FUNCTION * Outputs the code that accesses the object register with direct inline expansion instead of function call, and generates an object file. * When there is no #pragma directive, the register direct reference function is regarded as an ordinary function. EFFECT * Due to the C description, register access can be performed easily. USAGE * This function is described in the same format as a function call (Refer to Register direct reference function list later in this chapter). There are 21 types of register direct reference function names.
_ _geta, _ _seta, _ _getax, _ _setax, _ _getcy, _ _setcy, _ _set1cy, _ _clr1cy _ _not1cy, _ _inca, _ _deca, _ _rora, _ _rorca, _ _rola, _ _rolca, _ _shla _ _shra, _ _ashra, _ _nega, _ _coma, _ _absa * Use of the register direct reference function is declared by using the #pragma realregister directive in a module. However, the following items can be described before the #pragma realregister directive. * Comments * Other #pragma directives * Preprocessing directives that neither define nor reference variables or functions EXAMPLE (C source) #pragma realregister unsigned char c = 0x88, void main () { _ _seta (c) ; _ _shla () ; d = _ _geta () ; if (_ _getcy () ) { e=1; } } /* Sets the variable of C in A register /* Logically shifts 1 bit to left /* Refers CY (checks overflow) /* Sets e to 1 when CY = = 1 */ */ */ */ d, e ;
/* Sets the value of A register in variable d */
User's Manual U14872EJ1V0UM
411
CHAPTER 11
EXTENDED FUNCTIONS
Register Direct Reference Function
#pragma realregister
(Output object of compiler) _main : ; line ; line ; line ; line ; line 5 : _ _seta (c) ; mov add mov bnc 9 mov mov ?L0003 : ; line ; line 10 : } 11 : } ret a, #01H !_e, a a, !_c /* Logically shift 1 bit to left */ a, a /* Sets value of A register in variable d */ */ */ !_d, a $?L0003 e = 1 ; /* Sets e to 1 when CY = = 1 ;1 6 : _ _shla () ; 7 : d = _ _geta () ; /* Sets the variable of C in A register */
8 : if (_ _getcy () ) {/* Refers CY (checks overflow)
[Register direct reference function list] (1) unsigned char _ _geta (void) ;
Obtains the value of the A register. (2) void _ _seta (unsigned char x) ;
Sets x in the A register. (3) unsigned int _ _getax (void) ;
Obtains the value of the AX register. (4) void _ _setax (unsigned int x) ;
Sets x in the AX register. (5) bit _ _getcy (void) ;
Obtains the value of the CY flag. (6) void _ _setcy (unsigned char x) ;
Sets the lower 1 bit of x in the CY flag. (7) void _ _set1cy (void) ;
Generates the set1 CY instruction.
412
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Register Direct Reference Function
#pragma realregister
(8) void
_ _clr1cy (void) ;
Generates the clr1 CY instruction. (9) void _ _not1cy (void) ;
Generates the not1 CY instruction. (10) void _ _inca (void) ;
Generates the inc a instruction. (11) void _ _deca (void) ;
Generates the dec a instruction. (12) void _ _rora (void) ;
Generates 1 ror a, instruction. (13) void _ _rorca (void) ;
Generates 1 rorc a, instruction. (14) void _ _rola (void) ;
Generates 1 rol a, instruction. (15) void _ _rolca (void) ;
Generates 1 rolc a, instruction. (16) void _ _shla (void) ;
Generates the code that performs logical-shift of the A register 1 bit to the left. (17) void _ _shra (void) ;
Generates the code that performs a logical-shift of the A register 1 bit to the right. (18) void _ _ashra (void) ;
Generates the code that performs an arithmetic-shift of the A register 1 bit to the right. (19) void _ _nega (void) ;
Generates the code that obtains 2's complement in the A register. (20) void _ _coma (void) ;
Generates the code that obtains 1's complement in the A register. (21) void _ _absa (void) ;
Generates the code that obtains the absolute value of the A register.
User's Manual U14872EJ1V0UM
413
CHAPTER 11
EXTENDED FUNCTIONS
Register Direct Reference Function
#pragma realregister
RESTRICTIONS * The function name of a register direct reference cannot be not used as a function name. The register direct reference function is described in lowercase letters. A function described in uppercase letters are regarded as an ordinary function. * The values of the A and AX registers and CY flag that are set by the _ _ seta, _ _setax, and _ _setcy functions are not retained in the next code generation. * The timing that is referenced by the A and AX registers and CY flag with the _ _ geta, _ _getax, and _ _getcy functions, corresponds to the evaluation sequence of the expression. COMPATIBILITY * If the register direct reference function is not used, modification is not necessary. * To change to the register direct referencing function, modify according to USAGE above. * Register direct reference function names can be used as function names by deleting the #pragma realregister directive or delimiting #ifdef. * To use pragma realregister as a register direct reference function, modify the program according to the specifications of each C compiler (#asm, #endasm, or asm();, etc.). CAUTION * There is no guarantee that CY, A, AX will be saved as intended before the register direct reference function is executed. Accordingly, it is recommended to use this function before values change by describing it in the first term of the expression.
414
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(30) Memory manipulation function
Memory Manipulation Function
#pragma inline
FUNCTION * An object file is generated by the output of the standard library memory manipulation functions memcpy and memset with direct inline expansion instead of function call. * When there is no #pragma directive, the code that calls the standard library functions is generated. EFFECT * Compared with when a standard library function is called, the execution speed is improved. * Object code is reduced if a constant is specified for the specified character number. USAGE * The function is described in the source in the same format as a function call. * The following items can be described before #pragma inline. * Comments * Other #pragma directives * Preprocessing directives that neither define nor reference variables or functions EXAMPLE (C source) #pragma inline char ary1[100], ary2[100]; void main() { memset(ary1, `A', 50); memcpy(ary1, ary2, 50); }
User's Manual U14872EJ1V0UM
415
CHAPTER 11
EXTENDED FUNCTIONS
Memory Manipulation Function
#pragma inline
(Output object of compiler) When -SM is not specified _main: push ;line 5: movw mov mov mov incw dbnz ;line 6: movw movw mov mov mov incw incw dbnz ;line 7: pop ret hl memset(ary1, `A', 50); de,#_ary1 a, #041H c, #032H [de], a de c, $$-2 memcpy(ary1, ary2, 50); de, #_ary1 hl, #_ary2 c, #032H a, [hl] [de], a de hl c, $$-4 } hl ; 50 ; 65 ; 50
416
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Memory Manipulation Function
#pragma inline
When -SM is specified _main: push ;line 5: movw mov mov mov incw dbnz ;line 6: movw movw mov mov mov incw incw dbnz ;line 7: pop ret de memset(ary1, `A', 50); hl,#_ary1 a, #041H c, #032H [hl], a hl c, $$-2 memcpy(ary1, ary2, 50); hl, #_ary1 de, #_ary2 c, #032H a, [de] [hl], a de hl c, $$-4 } de ; 50 ; 65 ; 50
COMPATIBILITY * Modification is not needed if the memory manipulation function is not used. * When changing the memory manipulation function, modify according to USAGE above. * Delete the #pragma inline directive or delimit it with #ifdef.
User's Manual U14872EJ1V0UM
417
CHAPTER 11
EXTENDED FUNCTIONS
(31) Absolute address allocation specification
Absolute Address Allocation Specification
_ _directmap
FUNCTION * The initial value of an external variable declared by _ _directmap and a static variable in a function is regarded as the allocation address specification, and variables are allocated to the specified addresses. * The _ _directmap variable in the C source is treated as an ordinary variable. * Because the initial value is regarded as the allocation address specification, the initial value cannot be defined and remains an undefined value. * The specifiable address specification range, secured area range linked by the module for securing the area for the specified addresses, and variable duplication check range are shown below.
Address Specification Range 0x80 to 0xffff Secured Area Range 0xfd00 to 0xfeff Duplication Check Range 0xf000 to 0xfeff
* If the address specification is outside the address specification range, an F799 error is output. * If the allocation address of a variable declared by _ _directmap is duplicated and is within the duplication check range, a W762 warning message is output and the name of the duplicated variable is displayed. * If the address specification range is inside the saddr area, the _ _sreg declaration is made automatically and the saddr instruction is generated. * If char/unsigned char/short/unsigned short/int/unsigned int/long/unsigned long type variables declared by _ _directmap are bit referenced, sreg/_ _sreg must be specified along with _ _directmap. If they are not, an error occurs. EFFECT One or more variables can be allocated to the same arbitrary address.
418
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Absolute Address Allocation Specification
_ _directmap
USAGE * Declare _ _directmap in the module in which the variable to be allocated in an absolute address is to be defined. _ _directmap Type name Variable name _ _directmap static Type name Variable name _ _directmap _ _sreg Type name Variable name _ _directmap _ _sreg static Type name = Allocation address specification; = Allocation address specification; = Allocation address specification; Variable name = Allocation address specification;
* If _ _directmap is declared for a structure/union/array, specify the address in braces {}. * _ _directmap does not have to be declared in a module in which a _ _directmap external variable is referenced, so only declare extern. extern Type name Variable name; extern _ _sreg Type name Variable name; * To generate the saddr instruction in a module in which a _ _directmap external variable allocated inside the saddr area is referenced, _ _sreg must be used together to make extern_ _sreg Type name Variable name;. EXAMPLE (C source) _ _directmap char c = 0xfe00; _ _directmap _ _sreg char d = 0xfe20; _ _directmap _ _sreg char e = 0xfe21; _ _directmap struct x { char a; char b; } xx = {0xfe30}; void main() { c = 1; d = 0x12; e.5 = 1; xx.a = 5; xx.b = 10; }
User's Manual U14872EJ1V0UM
419
CHAPTER 11
EXTENDED FUNCTIONS
Absolute Address Allocation Specification
_ _directmap
(Output object) PUBLIC PUBLIC PUBLIC PUBLIC PUBLIC _c _d _e _xx EQU EQU EQU EQU EXTRN EXTRN EXTRN EXTRN EXTRN @@CODE CSEG _main: ;line 10: mov mov ;line ;line ;line ;line ;line 11: mov 12: set1 13: mov 14: mov 15: ret c = 1; a,#01H ;1 !_c,a d = 0x12; _d,#012H e.5 = 1; _e.5 xx.a = 5; _xx,#05H xx.b = 10; _xx+1,#0AH } ; saddr instruction output because address specified in saddr area ; saddr instruction output because address specified in saddr area ; Bit manipulation possible because _ _sreg also used ; saddr instruction output because address specified in saddr area _c _d _e _xx _main 0FE00H 0FE20H 0FE21H 0FE30H _ _mmfe00 _ _mmfe20 _ _mmfe21 _ _mmfe30 _ _mmfe31 ; Addresses for variables declared by _ _directmap ; are defined by EQU ; ; ; EXTRN output for linking secured area modules ; ; ; ;
420
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Absolute Address Allocation Specification
_ _directmap
RESTRICTIONS * _ _directmap cannot be specified for function arguments, return values, or automatic variables. specified in these cases, an error occurs. * If short/unsigned short/int/unsigned int/long/unsigned long type variables are allocated to odd addresses, the correct code will be generated in the file declared by _ _directmap, but illegal code will be generated if these variables are referenced by an extern declaration from an external file. * If an address outside the secured area range is specified, the variable area will not be secured, making it necessary to either describe a directive file or create a separate module for securing the area. COMPATIBILITY * No modification is necessary if the keyword _ _directmap is not used. * To change to the _ _directmap variable, modify according to USAGE above. * Compatibility can be attained using #define (refer to 11.6 Modifications of C Source for details). * To use _ _directmap as the absolute address allocation specification, modify the program according to the specifications of each compiler. If it is
User's Manual U14872EJ1V0UM
421
CHAPTER 11
EXTENDED FUNCTIONS
(32) Static model expansion specification
Static Model Expansion Specification
-ZM
FUNCTION * The 8-byte saddr area of _@NRAT00 to _@NRAT07 is secured as area reserved by the compiler for arguments and work. * Temporary variables can be used by declaring _ _temp for arguments and automatic variables (refer to 11.5 (33) Temporary variables for details). * The number of argument declarations that can be described ranges from 3 to 6 for int-sized variables and 3 to 9 for char-sized variables. The 4th and subsequent arguments are set by the calling side to the area of _@NRAT00 to _@NRAT05 and copied by the called side to a separate area. However, if _ _temp has been declared for a leaf function or an argument, the called side will not copy the argument, and the _@NRATxx area where the argument was set will be used as is. * Structures and unions that are 2 bytes or smaller can be described for arguments. * Structures and unions can be described for function return values. If the structures and unions are 2 bytes or smaller, the value will be returned. If 3 bytes or larger the return value will be stored in a static area secured for storing return values and returned to the top address of that area. * The 8-byte area of _@NRAT00 to _@NRAT07 is also used as the leaf function shared area. In shared-area allocation, the 8-byte area of _@NRAT00 to _@NRAT07 is allocated to first, and then the _@KREGxx area secured by specifying the -SM option. * Arrays, unions, and structures can also be allocated to _@NRATxx and _@KREGxx, provided their size fits into the _@KREGxx area secured by specifying _@NRATxx and -SM. * Interrupt functions that are targeted for saving are shown in Table 11-15 below. Table 11-15. Interrupt Functions Targeted for Saving
Restore/Save Area NO BANK With Function Call -ZM1 Registers used All registers Entire _@NRATxx area Entire _@KREGxx area _@KREGxx area used x x x x x x x -ZM2 x x Without Function Call -ZM1 x x x x -ZM2 x x x
: x:
Saved Not saved
422
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Static Model Expansion Specification
-ZM
Note, however, that when #pragma interrupt is specified, the interrupt functions that are targeted for saving can be limited by specifying as follows. SAVE_R (save/restore targets limited to registers) SAVE_RN (save/restore targets limited to registers and _@NRATxx). * The only difference between the -ZM1 and -ZM2 options is in the treatment of the _@KREGxx area secured by specifying -SM. When the -ZM1 option is specified, the _@KREGxx area is only used for leaf function shared area. When the -ZM2 option is specified, the _@KREGxx area is saved/restored and arguments and automatic variables are allocated there (compatibility with the -QR option in the normal model). * If the -ZM option is specified when the -SM option has not been specified, a W055 warning message is output and the -ZM option specification is ignored. EFFECT Restrictions on existing static models can be relaxed, improving descriptiveness. USAGE Specify the -ZM option during compilation. EXAMPLE 1 (C source) char funcl(char a, char b, char c, char d, char e); char func2(char a, char b, char c, char d); void main() { char a = 1, b = 2, c = 3, d = 4, e = 5, r; r = func1(a, b, c, d, e); } char func1(char a, char b, char c, char d, char e) { char r; r = func2(a, b, c, d); return e + r; } char func2(char a, char b, char c, char d) { return a + b + c + d; }
User's Manual U14872EJ1V0UM
423
CHAPTER 11
EXTENDED FUNCTIONS
Static Model Expansion Specification
-ZM
(Output object) When -SM8, -ZM1, and -QC are specified _main: ; line mov mov inc mov inc mov inc mov inc mov ; line ; line mov mov mov mov movw mov movw mov call mov ; line ret ; line ; line _func1: mov movw mov movw mov mov !L0011,a ax,bc !L0012,a ax,hl !L0013,a a,_@NRAT00 ; Copies to the static area 9 : char func1(char a, char b, char c, char d, char e) 10 : { 8:} 6: 7: r = func1(a, b, c, d, e); _@NRAT01,a a,!L0006 _@NRAT00,a a,!L0005 hl,ax a,!L0004 bc,ax a,!L0003 !_func1 !L0008,a ; r ; a ; b ; Sets the 5th argument to the saddr area for receiving and passing arguments ; d and passing arguments ; c ; Sets the 4th argument to the saddr area for receiving 5: char a = 1, b = 2, c = 3, d = 4, e = 5, r; a,#01H !L0003,a a !L0004,a a !L0005,a a !L0006,a a !L0007,a ; e ; d ; c ; b ;1 ; a
424
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Static Model Expansion Specification
-ZM
(Output object ...continued) mov !L0014,a mov mov ; line ; line ; line 11 : 12 : 13 : mov mov mov movw mov movw mov call mov ; line ; line 14 : add 15 : } ret ; line ; line _func2: mov movw mov movw mov ; line 18 : mov add add add ; line 19 : } ret _@NRAT01,a ax,bc _@NRAT02,a ax,hl _@NRAT03,a return a + b + c + d; a,_@NRAT01 a,_@NRAT02 a,_@NRAT03 a,_@NRAT00 ;a ;b ;c ;d Uses _@NRAT00 for the leaf function 16 : char func2(char a, char b, char c, char d) 17 : { r = func2(a, b, c, d); a,!L0014 _@NRAT00,a a,!L0013 hl,ax a,!L0012 bc,ax a,!L0011 !_func2 !L0016,a return e + r; a,!L0015 ;e ;r ;a ;b ;d ; Sets the 4th argument to the saddr area for receiving and passing arguments ;c a,_@NRAT01 !L0015,a char r; ; ; Copies to the static area ;
User's Manual U14872EJ1V0UM
425
CHAPTER 11
EXTENDED FUNCTIONS
Static Model Expansion Specification
-ZM
(Output object ...continued) When -SM8, -ZM2, -QC are specified @@CODE _main: movw push movw push movw push ; line mov mov mov mov mov ; line ; line mov mov mov mov mov movw mov movw mov call mov ; line pop movw pop movw pop movw ret 8:} ax _@KREG14,ax ax _@KREG12,ax ax _@KREG10,ax ; ; Restores the _@KREG10 to _@KREG15 areas ; ; ; ; 6: 7: r = func1(a, b, c, d, e); a,_@KREG11 _@NRAT01,a a,_@KREG12 _@NRAT00,a a,_@KREG13 hl,ax a,_@KREG14 bc,ax a,_@KREG15 !_func1 _@KREG10,a ;r ;a ;b ;e ; Sets the 5th argument to the saddr area for receiving and passing arguments ;d ; Sets the 4th argument to the saddr area for receiving and passing arguments ;c 5: ax,_@KREG10 ax ax,_@KREG12 ax ax,_@KREG14 ax _@KREG15,#01H _@KREG14,#02H _@KREG13,#03H _@KREG12,#04H _@KREG11,#05H ; ; Saves the _@KREG10 to _@KREG15 areas ; ; ; ; ; a,1 ; b,2 ; c,3 ; d,4 ; e,5 Allocates variables to _@KREG11 to _@KREG15 CSEG
char a = 1, b = 2, c = 3, d = 4, e = 5, r;
426
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Static Model Expansion Specification
-ZM
(Output object ...continued) ; line ; line _func1: mov movw push movw push movw push mov mov movw mov movw mov mov mov mov mov ; line ; line ; line 11 : 12 : 13 : mov mov mov movw mov movw mov call mov ; line 14 : add r = func2(a, b, c, d); a,_@KREG12 _@NRAT00,a a,_@KREG13 hl,ax a,_@KREG14 bc,ax a,_@KREG15 !_func2 _@KREG10,a return e + r; a,_@KREG11 ;e ;r ;a ;b ;d ; Sets the 4th argument to the saddr area for receiving and passing arguments ;c _@NRAT06,a ax,_@KREG10 ax ax,_@KREG12 ax ax,_@KREG14 ax a,_@NRAT06 _@KREG15,a ax,bc _@KREG14,a ax,hl _@KREG13,a a,_@NRAT00 _@KREG12,a a,_@NRAT01 _@KREG11,a char r; ; Copies to _@KREG12 ; ; Copies to _@KREG11 ; ; Saves register a ; ; Saves the _@KREG10 to _@KREG15 areas ; ; ; ; ; Restores register a 9 : char func1(char a, char b, char c, char d, char e) 10 : {
User's Manual U14872EJ1V0UM
427
CHAPTER 11
EXTENDED FUNCTIONS
Static Model Expansion Specification
-ZM
(Output object ...continued) L0004: ; line 15 : } movw pop movw pop movw pop movw movw ret ; line ; line _func2: mov movw mov movw mov ; line 18 : mov add add add L0006: ; line 19 : } ret _@NRAT01,a ax,bc _@NRAT02,a ax,hl _@NRAT03,a return a + b + c + d; a,_@NRAT01 a,_@NRAT02 a,_@NRAT03 a,_@NRAT00 ;a ;b ;c ;d Uses _@NRAT00 for the leaf function 16 : char func2(char a, char b, char c, char d) 17 : { hl,ax ax _@KREG14,ax ax _@KREG12,ax ax _@KREG10,ax ax,hl ; Saves register a ; ; Restores the _@KREG10 to _@KREG15 areas ; ; ; ; ; Restores register a
428
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Static Model Expansion Specification
-ZM
EXAMPLE 2 (C source) _ _sreg struct x { unsigned char a; unsigned char b:1; unsigned char c:1; } xx,yy; _ _sreg struct y { int a; int b; } ss, tt; struct x func1(struct x); struct y func2(); void main() { yy = func1(xx); tt = func2(); } struct x func1(struct x aa) { aa.a = 0x12; aa.b = 0; aa.c = 1; return aa; } struct y func2() { return tt; }
User's Manual U14872EJ1V0UM
429
CHAPTER 11
EXTENDED FUNCTIONS
Static Model Expansion Specification
-ZM
(Output object) When -SM and -ZM are specified @@CODE CSEG _main: ;line 14: yy = func1(xx); movw call movw ;line call movw push movw mov mov mov incw incw dbnz pop ;line ;line ;line _func1: movw ;line ;line ;line ;line ;line ;line ;line mov clr1 set1 movw ret 24: struct y func2() 25: { _@NRAT00,ax _@NRAT00,#012H _@NRAT01.0 _@NRAT01.1 ax,_@NRAT00 ; aa Value returned because 2 bytes or smaller ; aa,18 19: aa.a = 0x12; 20: aa.b = 0; 21: aa.c = 1; 22: return aa; 23:} ret 17: struct x func1(struct x aa) 18: { ax,_xx !_func1 _yy,ax !_func2 hl,ax de de,#_tt c,#04H ;4 a,[hl] [de],a hl de c,$$-4 de
15: tt = func2();
16: }
430
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Static Model Expansion Specification
-ZM
(Output object ...continued) ;line 26: return tt; movw push movw mov mov mov incw incw dbnz pop movw ;line ret hl,#_tt de de,#L0007 c,#04H ;4 a,[hl] [de],a hl de c,$$-4 de ax,#L0007 ; Returns top address of static area ; Return value copied to secured static area because ; 3 bytes or larger
27: }
COMPATIBILITY * The source program need not be modified. * The source program need not be modified.
User's Manual U14872EJ1V0UM
431
CHAPTER 11
EXTENDED FUNCTIONS
(33) Temporary variables
Temporary Variables
_ _temp
FUNCTION * Arguments and automatic variables are allocated to the area of _@NRAT00 to _@NRAT07, regardless of whether they correspond to a leaf function. If arguments and automatic variables are not allocated to the area of _@NRAT00 to _@NRAT07 they will be treated in the same way as when _ _temp is not declared. * The values of arguments and automatic variables declared by _ _temp are discarded upon a function call. * _ _temp cannot be declared for external and static variables. * If _ _sreg is declared as well, char/unsigned char/short/unsigned short/int/unsigned int variables can be bit manipulated. * If _ _temp is declared when the -SM and -ZM options have not been specified, a W339 warning message is output and the _ _temp declaration in the file is disregarded. EFFECT * Because arguments and automatic variables declared by _ _temp share the area of _@NRAT00 to _@NRAT07, an argument and automatic variable area can be reserved. * If the sections containing arguments and those containing automatic variables are clearly identified and the _ _temp declaration is applied to variables that do not require a guaranteed value match before and after a function call, memory can be reserved. USAGE Specify the -SM and -ZM options during compilation and declare _ _temp for arguments and automatic variables. EXAMPLE (C source) void func1(_ _temp char a, char b, char c, _ _sreg _ _temp char d); void func2(char a); void main() { func1(1, 2, 3, 4); } void func1(_ _temp char a, char b, char c, _ _sreg _ _temp char d) { _ _temp char r; d.1 = 0; r = a + b + c + d; func2(r); } void func2(char r) { int a = 1, b = 2; r++; }
432
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Temporary Variables
_ _temp
(Output object) When -SM, -ZM, and -QC are specified @@CODE _main: ; line mov mov mov mov sub call ; line ret ; line ; line _func1: mov movw mov movw mov ; line ; line ; line ; line 9: 10 : 11 : clr1 12 : mov add add add mov ; line 13 : call d.1 = 0; _@NRAT00.1 r = a + b + c + d; a,_@NRAT01 a,!L0005 a,!L0006 a,_@NRAT00 _@NRAT02,a func2(r); !_func2 ; Values in _@NRAT00 to _@NRAT02 are changed ; after return ; line ; line ; line 14 : } ret 15 : void func2(char r) 16 : { ;a ;b ;c ;d ;r _@NRAT01,a ax,bc !L0005,a ax,hl !L0006,a ; Argument allocated to _@NRAT00 is unchanged _ _temp char r; ; Allocates to _@NRAT01 7 : void func1(_ _temp char a, char b, char c, _ _sreg _ _temp char d) 8:{ 6:} 5: func1(1, 2, 3, 4); a,#04H h,#03H b,#02H a,#03H !_func1 ;4 ;3 ;2 ;3 _@NRAT00,a CSEG
User's Manual U14872EJ1V0UM
433
CHAPTER 11
EXTENDED FUNCTIONS
Temporary Variables
_ _temp
(Output object ...continued) _func2: mov ; line 17 : movw movw incw movw ; line ; line 18 : inc 19 : } ret _@NRAT00,a int a = 1, b = 2; ax,#01H ; 1 _@NRAT02,ax ax _@NRAT04,ax r++; _@NRAT00 ;b ;a
RESTRICTIONS If there are 3 arguments or fewer when a function is called, arguments and automatic variables declared by _ _temp can be described for the arguments at function call. If there are 4 or more arguments, because the values of the arguments could be discarded during argument evaluation, values described cannot be guaranteed. COMPATIBILITY * Modification is not necessary if the reserved word _ _temp is not used. * To change to a temporary variable, modify according to USAGE above. * Compatibility can be attained using #define (refer to 11.6 Modifications of C Source for details). This modification means that the _ _temp variable is treated as an ordinary variable.
434
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(34) Library supporting prologue/epilogue
Library Supporting Prologue/Epilogue
-ZD
FUNCTION * A specified pattern of the prologue/epilogue code can be replaced with a library call. * The number of callt entries that users can use is reduced by two in the case of a normal model and up to ten in the case of a static model. * The library replacement patterns in the case of a normal model are as follows. HL,_@KREGxx save/copy, stack frame secure HL,_@KREGxx restore, stack frame release callt [@@cprep2] callt [@@cdisp2]
* In the case of a static model, arguments are allocated to _@NRATxx and _@KREGxx so that the first 3 arguments accord with the patterns described below. When char and int are mixed, the allocation interval is adjusted so that it accords with the patterns of multiple int type arguments. * The library replacement pattern in the case of a static model is as follows. (For char 2 arguments) mov movw mov mov movw mov _@NRAT00,a ax,bc _@NRAT01,a _@KREG15,a ax,bc _@KREG14,a callt [@@krcp2] callt [@@nrcp2]
(For char 3 arguments) mov movw mov movw mov mov movw mov movw mov mov movw mov movw mov _@NRAT05,a ax,bc _@NRAT06,a ax,hl _@NRAT07,a _@KREG15,a ax,bc _@KREG14,a ax,hl _@KREG13,a _@NRAT06,a ax,bc _@NRAT07,a ax,hl _@KREG15,a call !@@nkrc3 callt [@@krcp3] callt [@@nrcp3]
User's Manual U14872EJ1V0UM
435
CHAPTER 11
EXTENDED FUNCTIONS
Library Supporting Prologue/Epilogue
-ZD
(For int 2 arguments) movw movw movw movw movw movw _@NRAT00,ax ax,bc _@NRAT02,ax _@KREG14,ax ax,bc _@KREG12,ax callt [@@krip2] callt [@@nrip2]
(For int 3 arguments) movw movw movw movw movw movw movw movw movw movw movw movw movw movw movw movw movw movw movw movw _@NRAT02,ax ax,bc _@NRAT04,ax ax,hl _@NRAT06,ax _@KREG14,ax ax,bc _@KREG12,ax ax,hl _@KREG10,ax _@NRAT04,ax ax,bc _@NRAT06,ax ax,hl _@KREG14,ax _@NRAT06,ax ax,bc _@KREG14,ax ax,hl _@KREG12,ax call !@@nkri32 call !@@nkri31 callt [@@krip3] callt [@@nrip3]
436
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Library Supporting Prologue/Epilogue
-ZD
(For save/restore) _@NRAT00 to _@NRAT07 save callt [@@nrsave] callt [@@nrload] call !@@krs02 call !@@krs04 call !@@krs04i call !@@krs06 call !@@krs06i call !@@krs08 call !@@krs08i call !@@krs10 call !@@krs10i call !@@krs12 call !@@krs12i call !@@krs14 call !@@krs14i call !@@krs16 call !@@krs16i call !@@krl02 call !@@krl04 call !@@krl04i call !@@krl06 call !@@krl06i call !@@krl08 call !@@krl08i call !@@krl10 call !@@krl10i call !@@krl12 call !@@krl12i call !@@krl14 call !@@krl14i call !@@krl16 call !@@krl16i
_@NRAT00 to _@NRAT07 restore _@KREG14 to 15 save _@KREG12 to 15 save
_@KREG10 to 15 save
_@KREG08 to 15 save
_@KREG06 to 15 save
_@KREG04 to 15 save
_@KREG02 to 15 save
_@KREG00 to 15 save
_@KREG14 to 15 restore _@KREG12 to 15 restore
_@KREG10 to 15 restore
_@KREG08 to 15 restore
_@KREG06 to 15 restore
_@KREG04 to 15 restore
_@KREG02 to 15 restore
_@KREG00 to 15 restore
User's Manual U14872EJ1V0UM
437
CHAPTER 11
EXTENDED FUNCTIONS
Library Supporting Prologue/Epilogue
-ZD
EFFECT By replacing prologue and epilogue code with a library, object code can be shortened. USAGE Specify the -ZD option during compilation. EXAMPLE 1 (C source) int func1(int a, int b, int c); int func2(int a, int b, int c); void main() { int r; r = func1(1, 2, 3); } int func1(int a, int b, int c) { return func2(a+1, b+1, c+1); } int func2(int a, int b, int c) { return a+b+c; }
438
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Library Supporting Prologue/Epilogue
-ZD
(Output object) (When -SM, -ZM2D, and -QC are specified) @@CODE CSEG _main: movw push ;line ;line ;line 5: 6: 7: movw movw movw call movw ;line pop movw ret ;line ;line _func1: call callt ;line 11: movw incw movw movw incw movw movw incw call L0004: ;line ret ;line ;line _func2: callt [@@nrip3]
User's Manual U14872EJ1V0UM
ax,_@KREG14 ax int r; r = func1(1, 2, 3); hl,#03H ; 3 bc,#02H ; 2 ax,#01H ; 1 !_func1 _@KREG14,ax } ax _@KREG14,ax int func1(int a, int b, int c) { !@@krs06 [@@krip3] return func2(a+1, b+1, c+1); ax,_@KREG10 ax hl,ax ax,_@KREG12 ax bc,ax ax,_@KREG14 ax !_func2 } !@@krl06 int func2(int a, int b, int c) { ;a ;b ;c ;r
8:
9: 10:
12: call 13: 14:
439
CHAPTER 11
EXTENDED FUNCTIONS
Library Supporting Prologue/Epilogue
-ZD
(Output object ...continued) ;line xch add xch addc xch add xch addc L0006: ;line ret 16: } 15: movw return a+b+c; ax, _@NRAT02 a,x a, _@NRAT04 a,x a, _@NRAT05 a,x a, _@NRAT06 a,x a, _@NRAT07 ;c ;c ;b ;b ;a
EXAMPLE 2 (C source) int func(register int a, register int b); void main() { register int a = 1, b = 2, c = 3,r; r = func(a, b); } int func(register int a, register int b) { register int r; r = a + b; return r; }
440
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Library Supporting Prologue/Epilogue
-ZD
(Output object) When -QR and -ZD are specified
@@CODE CSEG
_main: movw callt ; line 4: movw
movw
de,#03100H [@@cprep2] register int a = 1, b = 2, c = 3, r; hl,#01H ; 1
ax,hl
incw movw incw
movw
ax _@KREG14,ax ax
_@KREG12,ax ; c
;b
; line ; line
5: 6: movw push movw call pop movw movw r = func(a, b); ax,_@KREG14 ax ax,hl !_func ax ax,bc _@KREG10,ax } ax,#03100H [@@cdisp2] int func(register int a, register int b) { de,#0E840H [@@cprep2] register int r; r = a + b; ax,hl a,x a,_@KREG12 ; a a,x a,_@KREG13 ; a _@KREG14,ax ;r ;r ;b
; line
7: movw callt ret
; line ; line _func:
8: 9: movw callt
; line ; line ; line
10 : 11 : 12 : movw xch add xch addc movw
User's Manual U14872EJ1V0UM
441
CHAPTER 11
EXTENDED FUNCTIONS
Library Supporting Prologue/Epilogue
-ZD
(Output object ...continued) L0004: ; line 14 : movw callt ret } ax,#0E840H [@@cdisp2]
442
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
Library Supporting Prologue/Epilogue
-ZD
RESTRICTIONS * The optimization specification option -QL4 cannot be specified at the same time as the -ZD option. If it is specified, a W052 warning message is output and the -QL4 option is replaced with the -QL3 option and processed. CAUTION The argument copy pattern in the case of a static model will be pattern-matched only when register has not been specified for any of the first 3 arguments or _ _temp has been specified for all of the first 3 arguments. Therefore, because pattern matching will not be performed if the -QV option is specified or if register/_ _temp are partially specified for the first 3 arguments, it will no longer be possible to replace the -ZD option specification. COMPATIBILITY * The source program need not be modified. * To replace the prologue/epilogue code with a library, modify the source program according to USAGE above. * The source program need not be modified.
User's Manual U14872EJ1V0UM
443
CHAPTER 11
EXTENDED FUNCTIONS
11.6 Modifications of C Source
By using the extended functions of this C compiler, efficient object generation can be realized. However, these extended functions are intended for the 78K/0S Series. So, to use them for other devices, the C source may need to be modified. Here, how to make the C source portable from another C compiler to this C compiler and vice versa is explained. * #pragma
Note
If the other C compiler supports the #pragma preprocessing directive, the C source must be modified. The method and extent of modifications to the C source depend on the specifications of the other C compiler. * Extended specifications If the other C compiler has extended specifications such as addition of keywords, the C source must be modified. The method and extent of modifications to the C source depend on the specifications of the other C compiler. Note #pragma is one of the preprocessing directives supported by ANSI. The character string following #pragma is identified as a directive to the compiler. If the compiler does not support this directive, the #pragma directive is ignored and the compile will be continued until it properly ends. Because this C compiler has added keywords as the extended functions, the C source must be made portable to the other C compiler by deleting such keywords or delimiting them with #ifdef. EXAMPLE <1> To invalidate a keyword (the same applies to callf, sreg, noauto, and norec, etc.) #ifndef _ _K0S_ _ #define callt #endif <2> To change from one type to another #ifndef _ _K0S_ _ #define bit char #endif /* changes bit type to char type variable */ /* makes callt as ordinary function */
444
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
11.7 Function Call Interface
The following will be explained about the interface between functions at function call. 1. Return value (common in all the functions) 2. Ordinary function call interface (1) Passing arguments (2) Location and order of storing arguments (3) Location and order of storing automatic variables 3. noauto function call interface (1) Passing arguments (2) Location and order of storing arguments (3) Location and order of storing automatic variables 4. norec function call interface (1) Passing arguments (2) Location and order of storing arguments (3) Location and order of storing automatic variables 5. Static model function call interface (1) Passing arguments (2) Location and order of storing arguments (3) Location and order of storing automatic variables 6. Pascal function call interface
User's Manual U14872EJ1V0UM
445
CHAPTER 11
EXTENDED FUNCTIONS
11.7.1 Return value The function called stores the return value in the registers and carry flags as shown in Table 11-16. Table 11-16. Location of Storing Return Value
Model Type 1-byte integer 2-byte integer 4-byte integer BC (Lower) DE (Upper) BC BC (if copied to the area specific to the function, the start address of the structure or union) CY (carry flag) BC (Lower) DE (Upper) BC (Lower) DE (Upper) BC A AX Not supported Normal Model Static Model
Pointer Structure, union
AX Not supported
1 bit Floating-point number (float type)
CY (carry flag) Not supported
Floating-point number (double type)
Not supported
446
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
11.7.2 Ordinary function call interface When all the arguments are allocated to registers and there are no automatic variables, the ordinary function call interface is the same as noauto function call interface. (1) Passing arguments * There are two types of arguments: arguments that are allocated to registers and normal arguments. * An argument that is allocated to a register is an argument that has undergone register declaration and is allocated to a register or _@KREGxx as long as an allocatable register and _@KREGxx exist. However, arguments are allocated to _@KREGxx only when -QR is specified. Arguments that are allocated to a register or _@KREGxx are referred to as register arguments hereafter. * Refer to APPENDIX A LIST OF LABELS FOR saddr AREA for _@KREGxx. * The remaining arguments are allocated to a stack. * On the function call side, both the arguments declared with registers and the ordinary arguments are passed in the same manner. The second argument and later are passed via a stack, and the first argument is passed via a register or stack. * On the function definition side, arguments passed via register or stack are saved in the place where arguments are allocated. * Register arguments are copied to a register or _@KREGxx. Even when the arguments are passed via registers, register copying is necessary since the registers on the function caller (passing side) are different to those on the function definition side (receiving side). * Normal arguments are loaded on a stack. When an argument is passed via a stack, the area where the arguments are passed to becomes the area to which they are allocated. * Saving and restoring registers to which arguments are allocated is performed on the function definition side. * The location where the first argument is passed is shown in Table 11-17. Table 11-17. Location Where First Argument Is Passed (on Function Call Side)
Option Type 1-byte dataNote 2-byte dataNote 3-byte dataNote 4-byte data
Note
Normal Model
AX
AX, BC AX, BC AX, BC AX, BC Passed via stack
Floating-point number (float type) Floating-point number (double type) Others
Note
1- to 4-byte data includes structures, unions, and pointers.
User's Manual U14872EJ1V0UM
447
CHAPTER 11
EXTENDED FUNCTIONS
(2) Location and order of storing arguments * There are two types of arguments: arguments allocated to registers and ordinary arguments. Arguments allocated to registers are arguments declared with registers and arguments when -QV is specified. * The arguments not allocated to registers are allocated to stacks. The arguments allocated to stacks are placed on the stack sequentially from the last argument. * Saving and restoring registers to which arguments are allocated is performed on the function definition side. * On the function definition side, the arguments that are passed via a register or stack are stored in the area to which arguments are allocated. * The register arguments are copied to a register or _@KREGxx. Copying to _@KREGxx is performed only when -QR is specified. Even when the arguments are passed via registers, register copying is necessary since the registers on the function caller (passing side) are different to those on the function definition side (receiving side). * On the function caller side, both register arguments and normal arguments are passed using the same method. The second or later arguments are passed via a stack. The first argument is passed via a register or stack. Refer to Table 11-17 for the place where the first argument is passed. (Registers to be used) HL Arguments are not allocated to HL when there is a stack frame. (saddr area to be used) _@KREG12 to 15 (Allocation sequence) * Registers char type: * saddr area char type: long, float, double type: The sequence is _@KREG12, _@KREG13, _@KREG14, and _@KREG15. The sequence is _@KREG12 to 13 (lower)-_@KREG14 to 15 (higher). int, short, and enum type: The sequence is _@KREG12 to 13 and _@KREG14 to 15. The sequence is L-H. int, short, and enum type: HL
448
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(3) Location and order of storing automatic variables * There are two types of automatic variables: automatic variables to be allocated to registers and ordinary automatic variables. The automatic variables to be allocated to registers are ones which are declared with registers and automatic variables with -QV is specified. They are allocated to registers and _@KREGxx as long as there are allocable registers and _@KREGxx. _@KREGxx only when -QR is specified. The automatic variables allocated to registers and _@KREGxx are called register variables hereafter. * For _@KREGxx, refer to APPENDIX A LIST OF LABELS FOR saddr AREA. * Register variables are allocated after register arguments are allocated. Therefore, register variables are allocated to registers when there are excess registers after the allocation of register arguments. * The automatic variables not allocated to a register are allocated to a stack. * Saving and restoring registers and _@KREGxx to which automatic variables are allocated is performed on the function definition side. (a) Automatic variable allocation sequence The sequence of allocating automatic variables to _@KREGxx is as follows. (Registers to be used) HL Arguments are not allocated to HL when there is a stack frame. (saddr area to be used) _@KREG00 to 15 (Allocation sequence) * Registers char type: * saddr area char type: The sequence is _@KREG00, _@KREG01 ..., and _@KREG11. to 15. long, float, double type: The sequence is _@KREG00 to 03, _@KREG04 to 07, and _@KREG12 to 15. * The automatic variables that are allocated to a stack are loaded on the stack in the sequence of declaration. int, short, and enum type: The sequence is _@KREG00 to 01, _@KREG02 to 03 ... and _@KREG10 The sequence is L and H. int, short, and enum type: HL However, automatic variables are allocated to
User's Manual U14872EJ1V0UM
449
CHAPTER 11
EXTENDED FUNCTIONS
[Example] In the normal model (C source 1) void func0 (register int, int) ; void main () { func (0x1234, 0x5678) ; } void func (register int p1, int p2) { register int r ; int a ; r = p2 ; a = p1 ; }
(Output code) _main: ; line movw push movw call pop ; line ret ; line ; line _func0: push xch xch xch xch push movw push push movw movw hl a, x a, _@KREG12 a, x a, _@KREG13 ax ax, _@KREG14 ax ax ax, sp hl, ax ; Saves the saddr area for register variables ; Reserves the area for automatic variable a ; Allocates register argument p1 to _@KREG12 ; Saves the saddr area for register arguments 6: void func0 (register int p1, int p2) 7: { 4: func0 (0x1234, 0x5678) ; ax, #05678H ax ax, #01234H !_func0 ax 5: } ; 4660 ; 22136 ; Receives/passes an argument via a stack ; Passes the 1st argument to a register ; Function call ; Receives/passes an argument via a stack
450
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(Output code) (continued) ; line ; line ; line mov xch mov movw ; line movw mov xch mov ; line pop pop movw pop movw pop ret 8: register int r ; 9: int a ; 10: r = p2 ; a, [hl + 10] a, x a, [hl + 11] _@KREG14, ax ax, _@KREG12 [hl + 1], a a, x [hl], a 12: } ax ax _@KREG14, ax ax _@KREG12, ax hl ; Restores the saddr area for register arguments ; Restores the saddr area for register variables ; Releases the area for automatic variable a ;a ; Automatic variable a 11: a = p1 ; ; p1 ;a ; Assigns register argument _@KREG12 to ; p2 ;r ; to register variable _@KREG14 ; p2 ; Assigns argument p2, which is received/passed via ; a stack,
User's Manual U14872EJ1V0UM
451
CHAPTER 11
EXTENDED FUNCTIONS
(C source 2) void func1 (int, register int) ; void main () { func1 (0x1234, 0x5678) ; } void func1 (int p1, register int p2) { register int r ; int a ; r = p2 ; a = p1 ; }
(Output code) _main: ; line movw push movw call pop ; line ret ; line ; line _func1: push push movw push movw push push movw movw mov xch mov movw ; line ; line hl ax ax, _@KREG12 ax ax, _@KREG14 ax ax ax, sp hl, ax a, [hl + 12] a, x a, [hl + 13] _@KREG12, ax 8: register int r ; 9: int a ; ; Allocates the register argument to _@KREG12 ; Passes argument p2 from the stack to the saddr area ; Saves the saddr area for register arguments ; Reserves the area for automatic variable a ; Saves the saddr area for register arguments ; Loads 1st argument p1 on the stack 6: void func1 (int p1, register int p2) 7: { 4: func1 (0x1234, 0x5678) ; ax, #05678H ax ax, #01234H !_func1 ax 5: } ; 4660 ; 22136 ; Receives/passes an argument via a stack ; Passes the 1st argument to a register ; Function call ; Receives/passes an argument via a stack
452
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(Output code) (continued) ; line movw movw ; line mov mov xch mov mov ; line pop pop movw pop movw pop pop ret 10: r = p2 ; ax, _@KREG12 _@KREG14, ax 11: a = p1 ; a, [hl + 6] [hl] , a a, x a, [hl + 7] [hl + 1] , a 12: } ax ax _@KREG14, ax ax _@KREG12, ax ax hl ; Restores the saddr area for register arguments ; Restores the saddr area for register variables ; Releases area of automatic variable a ; p1 ;a ; Passes argument p1 (higher) from register ; to stack ; Automatic variable a (higher) ; p1 ;a ; Passes argument p1 (lower) from register ; to stack ; Automatic variable a (lower) ; p2 ;r ; Register variable _@KREG14
User's Manual U14872EJ1V0UM
453
CHAPTER 11
EXTENDED FUNCTIONS
11.7.3 noauto function call interface (normal model only) (1) Passing arguments * On the function caller, arguments are passed in the same way as ordinary functions. Ordinary function call interface. * On the function definition side, arguments passed via a register or stack are copied to a register as well as _@KREG12 to 15. Copying to _@KREG12 to 15 is performed only when -QR is specified. Even when the arguments are passed via registers, register copying is necessary since the registers on the function caller (passing side) are different to those on the function definition side (receiving side). * Saving and restoring registers to which arguments are allocated is performed on the function definition side. (2) Location and order of storing arguments * On the function definition side, all arguments are allocated to registers and _@KREG12 to 15. However, arguments are allocated to _@KREG12 to 15 only when -QR is specified. * If there are arguments that are not allocated to registers or _@KREG12 to 15 an error will result. * On the function caller, arguments are passed in the same way as in an ordinary function (Refer to 11.7.2 Ordinary function call interface). * On the function definition side, the arguments passed via a register or stack are copied to a register as well as _@KREG12 to 15. Even when the arguments are passed via registers, register copying is necessary since the registers on the function caller (passing side) are different to those on the function definition side (receiving side). * Saving and restoring registers to which arguments are allocated is performed on the function definition side. (Allocation sequence) * The allocation sequence is the same as for ordinary functions (refer to 11.7.2 Ordinary function call interface). Refer to 11.7.2
454
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(3) Location and order of storing automatic variables Automatic variables are allocated to registers and _@KREG12 to 15. OF LABELS FOR saddr AREA. Automatic variables are allocated to registers when there are excess registers after the allocation of arguments. When -QR is specified, automatic variables are also allocated to _@KREG12 to 15. If an automatic variable cannot be allocated to a register or _@KREG12 to 15, an error occurs. Saving and restoring the registers and _@KREG12 to 15 to which automatic variables are allocated is performed on the function definition side. (Allocation sequence) * The order of allocating automatic variables to registers is the same as the order of allocating arguments. * The automatic variables allocated to _@KREG12 to 15 are allocated in the order of declaration. [Example] (C source) noauto void func2 (int, int) ; void main () { func2 (0x1234, 0x5678) ; } noauto void func2 (int p1, int p2) { . . . } However, automatic variables are allocated to _@KREG12 to 15 only when -QR is specified. For _@KREG12 to 15, refer to APPENDIX A LIST
User's Manual U14872EJ1V0UM
455
CHAPTER 11
EXTENDED FUNCTIONS
(Output code) _main: ; line movw push movw call pop ; line ret ; line ; line _func2: push xch xch xch xch push movw movw mov xch mov movw . . . pop movw pop ret ax _@KREG12, ax hl ; Restores the saddr area for arguments ; Restores the register for arguments hl a, x a, _@KREG12 a, x a, _@KREG13 ax ax, sp hl, ax a, [hl + 6] a, x a, [hl + 7] hl, ax ; Argument p2 (higher) passed via a stack and received via a register ; Allocates arguments to HL ; Argument p2 (lower) passed via a stack and received via a register ; Allocates argument p1 to _@KREG13 (higher) ; Saves the saddr area for arguments ; Allocates argument p1 to _@KREG12 (lower) ; Saves a register for arguments 6: noauto void func2 (int p1, int p2) 7: { 4: func2 (0x1234, 0x5678) ; ax, #05678H ax ax, #01234H !_func2 ax 5: } ; 4660 ; 22136 ; Argument passed via a stack ; The first argument that is passed via a register ; Function call ; Argument passed via a stack
456
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
11.7.4 norec function call interface (normal model) (1) Passing arguments All arguments are allocated to _@NRARGx and _@RTARG6 and 7. On the function caller side, arguments are passed via register _@NRARGx. On the function definition side, arguments passed via registers are copied to registers, or to _@RTARG6 and 7 (Refer to APPENDIX A LIST OF LABELS FOR saddr AREA). (2) Location and order of storing arguments * On the function definition side, all arguments are allocated to registers, _@NRARGx, _@RTARG6 and 7. Arguments are allocated to _@NRARGx only when -QR is specified. * Arguments are allocated to _@RTARG6 and 7 only when there are arguments in DE (Refer to APPENDIX A LIST OF LABELS FOR saddr AREA). * If there are arguments that are not allocated to registers, _@NRARGx, _@RTARG6 and 7, an error will result. * On the function caller side, arguments are passed via registers and _@NRARGx. * On the function definition side, arguments that are passed via registers are copied to registers or _@RTARG6 and 7. Even when the arguments are passed via registers, register copying is necessary since the registers on the function caller side (passing side) are different to those in the function definition side (receiving side). If the arguments are passed via registers, the area where the arguments are passed becomes the area to which they are allocated. * If arguments can no longer be passed via a register, they can be allocated to _@NRARGx and passed via there. In this case, passing is carried out with registers and _@NRARGx intermingled. (Argument allocation sequence) * Arguments allocated to _@NRARGx are allocated in the sequence of declaration. * Arguments allocated to registers are allocated to registers, _@RTARG6 and 7 according to the following rules. (Registers to be used) * When one argument is used in char, int, short, enum, or pointer type: AX pass, DE receive _@RTARG6, 7 DE receive (Allocation sequence) * char, int, short, enum, and pointer type: In the sequence of DE, _@RTARG6 and 7 * When two or more arguments are used in char, int, short, enum, or pointer type: AX and DE pass
User's Manual U14872EJ1V0UM
457
CHAPTER 11
EXTENDED FUNCTIONS
(3) Location and order of storing automatic variables Automatic variables are allocated to registers and _@NRARGx as long as there are allocable registers and _@NRARGx. If there is no allocable register, they are allocated to _@NRATxx. However, automatic variables are allocated to _@NRARGx and _@NRATxx only when -QR is specified. For _@NRATxx, refer to APPENDIX A LIST OF LABELS FOR saddr AREA. If there is an automatic variable that cannot be allocated to a register, _@NRARGx and _@NRATxx, an error occurs. Saving and restoring registers to which automatic variables are allocated is performed on the function definition side. (Allocation sequence) * The order of allocating automatic variables to registers, _@RTARG6 to 7 is the same as the order of allocating arguments. * The automatic variables allocated to _@NRARGx, _@NRATxx are allocated in the order of declaration. [Example] In the normal model (C source) norec void func3 (char, int, char, int) ; void main () { func3 (0x12, 0x34, 0x56, 0x78) ; } norec void func3 (char p1, int p2, char p3, int p4) { int a ; a = p2 ; }
458
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(Output code) When -QR is specified _main : ; line movw movw mov movw mov call ret ; line ; line _func3 : mov ; line ; line movw movw ret _@RTARG6, a 8 : int a ; 9 : a = p2 ; ax, de _@NRARG2, ax ;a ; Argument p2 ; Automatic variable a ; Allocates the argument p1 to _@RTARG6 6 : norec void func3 (char p1, int p2, char p3, int p4) 7:{ 4 : func3 (0x12, 0x34, 0x56, 0x78) ; ax, #078H _@NRARG1, ax _@NRARG0, #056H de, #034H a, #012H !_func3 ; 86 ; 52 ; 18 ; Argument is passed via _@NRARG0 ; Argument is passed via register DE ; Argument is passed via register A ; Function call ; Argument is passed via _@NRARG1
User's Manual U14872EJ1V0UM
459
CHAPTER 11
EXTENDED FUNCTIONS
11.7.5 Static model function call interface (1) Passing arguments * On the function caller side, both the register arguments and the normal arguments are passed in the same way. There can be a maximum of three arguments, up to 6 bytes, and all arguments are passed via registers. * On the function definition side, the arguments passed via a register are stored in the area to which they are allocated. Register arguments are copied to registers. Even when the arguments are passed via registers, register copying is necessary since the registers on the function caller side (passing side) are different to those on the function definition side (receiving side). * Ordinary functions are allocated to the function-specific area. (2) Location and order of storing arguments (a) Argument storage location * There are two types of arguments: arguments to be allocated to registers and normal arguments. * The arguments allocated to registers are arguments that have undergone a register declaration. * On the function definition side, the arguments that are passed via a register or stack are stored in the area to which arguments are allocated. Register arguments are copied to a register. Even when the arguments are passed via registers, register copying is necessary since the registers on the function caller side (passing side) are different to those on the function definition side (receiving side). Normal arguments are allocated to the function-specific area. * Saving and restoring registers to which arguments/automatic variables are allocated is performed on the function definition side. * The remaining arguments are allocated to the function-specific area. * On the function caller side, both register arguments and normal arguments are passed in the same way. There can be a maximum of three arguments, up to 6 bytes, and all arguments are passed via a register. Table 11-18 shows the area to which arguments are passed. Table 11-18. Areas to Which Arguments Are Passed in Static Model
Data Size 1-byte dataNote 2-byte dataNote 4-byte dataNote First Argument A AX Second Argument B BC Third Argument H HL
Allocated to AX and BC and the remainder allocated to H or HL.
Note Neither structures nor unions are included in 1- to 4- byte data. (b) Argument allocation sequence * Arguments allocated to the function-specific area are allocated sequentially from the last argument. * Register arguments are allocated to register DE according to the following rules. (Registers to be used) DE (Allocation sequence) char type: sequence of D, E int, short, enum type: DE
460
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
(3) Location and order of storing automatic variables (a) Storage location of automatic variables * There are two types of automatic variables: automatic variables to be allocated to registers and normal automatic variables. * Automatic variables allocated to registers are automatic variables declared with registers and automatic variables when -QV is specified. * Register variables are allocated after register arguments are allocated. For this reason, the allocation of register variables to registers is performed only when registers are superfluous after register argument allocation. * The remaining automatic variables are allocated to the function-specific area. * Saving and restoring registers to which arguments are allocated is performed on the function definition side. (b) Automatic variable allocation sequence * Automatic variables are allocated to register DE according to the following rules. (Registers to be used) DE (Allocation sequence) char type: Sequence of E, D int, short, enum type: DE * The automatic variables that are allocated to the function-specific area are allocated in the sequence of declaration. [EXAMPLE 1] (C source) void func4 (register int, char) ; void main () { func4 (0x1234, 0x56) ; } void func4 (register int p1, char p2) { register char r ; int a ; r = p2 ; a = p1 ; }
User's Manual U14872EJ1V0UM
461
CHAPTER 11
EXTENDED FUNCTIONS
(Output code) @@DATA L0005 : L0006 : L0007 : ; line ; line ; line @@CODE _main : ; line mov movw call ; line ret ; line ; line _func4 : push movw movw mov ; line ; line ; line mov ; line movw movw callt ; line pop ret de de, ax ax, bc !L0005, a 8 : register char r ; 9 : int a ; 10 : r = p2 ; !L0006, a 11 : a = p1 ; ax, de hl, #L0007 [@@hlist] de ; Restores the register for register argument ;a ; Register argument p1 ; Automatic variable a ;r ; Automatic variable r ; Copy argument p2 to L0005 ; Saves register for register argument ; Allocates register argument p1 to DE 6 : void func4 (register int p1, char p2) 7:{ 4 : func4 (0x1234, 0x56) ; b, #056H ax, #01234H !_func4 5:} ; 86 ; 4660 ; Passes the second argument via register B ; Passes the first argument via register AX ; Function call DSEG DS DS DS (1) (1) (2) ; Argument p2 ; Automatic variable r ; Automatic variable a
1 : void func4 (register int, char) ; 2 : void main () 3:{ CSEG
12 : }
462
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
[EXAMPLE 2] (C source) void func5 (int, register char) ; void func(); void main () { func5 (0x1234, 0x56) ; } void func5 (int p1, register char p2) { register char r ; int a ; r = p2 ; a = p1 ; func(); }
(Output code) @@DATA L0005 : L0006 : ; line ; line ; line @@CODE _main : ; line 4 : func5 (0x1234, 0x56) ; mov movw call ; line ; line ; line _func5 : push movw callt movw de hl, #L0005 [@@hlist] ax, bc ; Saves a register for register variables and ; register arguments. ; Copies argument p1 to L0005 5:} ret 6 : void func5 (int p1, register char p2) 7:{ b, #056H ax, #01234H !_func5 ; 86 ; Passes the second argument via register B ; Function call ; 4660 ; Passes the first argument via register AX DSEG DS DS (2) (2)
1 : void func5 (int, register char) ; void func(); 2 : void main () 3:{ CSEG
User's Manual U14872EJ1V0UM
463
CHAPTER 11
EXTENDED FUNCTIONS
(Output code ...continued) mov ; line ; line ; line 9 : int a ; 10 : r = p2 ; movw mov ; line movw callt movw callt call ; line 12 : } pop ret de ; Restores the register for register arguments ax, de e, a hl, #L0005 [@@hlilo] hl, #L0006 [@@hlist] !_func ;a ; Automatic variable a ; p1 ; Register argument p2 ; Register variable r ; Argument p1 de, ax ; Allocates a register argument p2 to d.
8 : register char r ;
11 : a = p1 ; func();
464
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
11.7.6 Pascal function call interface The difference between this function interface and other function interfaces is that the correction of stacks used for loading of arguments when a function is called is done on the function side that was called, rather than the function caller side. All other points are the same as the function attributes specified at the same time. [Area to which arguments are allocated] [Sequence in which arguments are allocated] [Area to which automatic variables are allocated] [Sequence in which automatic variables are allocated] * If the noauto attribute is specified at the same time, the features are the same as when a noauto function is called (refer to 11.7.3 noauto function call interface). * If the noauto attribute is not specified at the same time, the features are the same when an ordinary function is called (refer to 11.7.2 Ordinary function call interface). EXAMPLE 1 (C source) _ _pascal void func0 (register int, int) ; void main () { func0 (0x1234, 0x5678) ; } _ _pascal void func0 (register int p1, int p2) { register int r ; int a ; r = p2 ; a = p1 ; }
User's Manual U14872EJ1V0UM
465
CHAPTER 11
EXTENDED FUNCTIONS
(Output code) When -QR option is specified _main: ; line 4 :func0 (0x1234, 0x5678) ; ax, #05678H ax ax, #01234H !_func0 } :_ _pascal void func0 (register int p1, int p2) :{ hl a, x a,_@KREG12 a, x a,_@KREG13 ax ax,_@KREG14 ax ax ax, sp hl, ax :register int r ; :int a; :r = p2; a, [hl + 10] a, x a, [hl + 11] _@KREG14, ax ax,_@KREG12 [hl + 1], a a, x [hl], a 12 :} ax ax _@KREG14, ax ax _@KREG12, ax hl de ax de ; Obtains the return address ; Corrects the stack consumed by arguments passed via a stack ; Reloads the return address ; Restores the saddr area for register arguments ; Restores the saddr area for register variables ; Releases the automatic variable a area ;a ; Assigned to automatic variable a 11 :a = p1 ; ; p1 ;a ; Register argument _@KREG12 ; p2 ;r ; Assigned to register variable _@KREG14 ; p2 ; Stack transfer argument p2 ; Saves the saddr area for register variables ; Reserves the automatic variable a area ; Allocates register argument p1 to _@KREG12 ; Saves the saddr area for register arguments ; 4660 ; 22136 ; Stack is passed via the argument ; The first argument that is passed via a register ; Function call ; Stack is not corrected here movw push movw call ; line ; line ; line _func0: push xch xch xch xch push movw push push movw movw ; line ; line ; line 8 9 10 5: 6 7
ret
mov xch mov movw ; line mov xch mov ; line pop pop movw pop movw pop pop pop push ret movw
466
User's Manual U14872EJ1V0UM
CHAPTER 11
EXTENDED FUNCTIONS
EXAMPLE 2 (C source) _ _pascal noauto void func2 (int, int) ; void main () { func2 (0x1234, 0x5678) ; } _ _pascal noauto void func2 (int p1, int p2) { . . . }
(Output code) When -QR option is specified _main: ; line 4 : func2 (0x1234, 0x5678) ; movw push movw call ; line ; line ; line _func2: push xch xch xch xch push movw movw mov xch hl a, x a,_@KREG12 a, x a,_@KREG13 ax ax, sp hl, ax a, [hl + 6] a, x ; Argument p2 (lower) passed via a stack ; and received by a register ; Allocates argument p1 to _@KREG13 (higher) ; Saves the saddr area for arguments ; Allocates argument p1 to _@KREG12 (lower) ; Saves the register for arguments 5:} ret 6 : _ _pascal noauto void func2 (int p1, int p2) 7:{ ax, #05678H ; 22136 ax ax, #01234H ; 4660 !_func2 ; Argument passed via a stack ; The first argument that is passed via a register ; Function call ; The stack is not corrected here
User's Manual U14872EJ1V0UM
467
CHAPTER 11
EXTENDED FUNCTIONS
(Output code ... continued) mov movw . . . pop movw pop pop pop push ret ax _@KREG12, ax hl de ax de ; Restores the saddr area for arguments ; Restores the register for arguments ; Obtains the return address ; Corrects the stack consumed by arguments passed via a stack ; Reloads the return address a, [hl + 7] hl, ax ; Argument p2 (higher) passed via a stack ; and received by a register ; Allocates arguments to HL
468
User's Manual U14872EJ1V0UM
CHAPTER 12
REFERENCING THE ASSEMBLER
This chapter describes how to link a program written in assembly language. If a function called from a C source program is written in another language, both object modules are linked by the linker. This chapter describes the procedure for calling a program written in another language from a program written in the C language and the procedure for calling a program written in the C language from a program written in another language. How to interface with another language by using the RA78K0S Assembler Package and this C compiler is described in this order: (1) Calling assembly language routines from the C language (2) Calling C language functions from assembly language (3) Referencing variables defined in the C language (4) Referencing variables defined in assembly language on the C language side (5) Cautions
User's Manual U14872EJ1V0UM
469
CHAPTER 12
REFERENCING THE ASSEMBLER
12.1 Accessing Arguments/Automatic Variables
The procedure to access arguments and automatic variables of this C compiler is described below. 12.1.1 Normal model * On the function call side, register arguments are passed in the same way as regular arguments. The first argument uses the following registers and stacks, and subsequent arguments are passed via stacks. Table 12-1. Passing Arguments (Function Call Side)
Type 1-byte, 2-byte data 3-byte, 4-byte data Floating-point number Others Passing Location (First Argument) AX AX, BC AX, BC Stack passing Passing Location (Second and Later Arguments) Stack passing Stack passing Stack passing Stack passing
Remark 1- to 4-byte data includes structures and unions. * On the function definition side, arguments passed via a register or stack are stored in the argument allocation location. Register arguments are copied to a register or saddr area (_@KREGxx). Even when passing is done via a register, the registers on the function call side (passing side) and the function definition side (receiving side) differ, and therefore register copying is performed. Normal arguments passed via a register are pushed to a stack on the function definition side. If passing is done via a stack, the passing location simply becomes the argument allocation location. Saving and restoring registers to which arguments are allocated is performed on the function definition side. * The arguments of functions and the values of automatic variables declared inside functions are stored in the following registers, saddr areas, or stack frames using an option. The base pointer used when storing in a stack frame uses the HL register. If the function argument is register-declared or specified by the -QV option and specified by the -QR option, it is allocated to the saddr area.
470
User's Manual U14872EJ1V0UM
CHAPTER 12
REFERENCING THE ASSEMBLER
Table 12-2. Storing of Arguments/Automatic Variables (Inside Called Function)
Option -QV (register allocation option) Argument/auto Variable Declared argument or automatic variable Storage Location HL register (only when base pointer is not required) HL register (only when base pointer is not required) Argument: _@KREG12 to 15 [0FEE4H to 0FEE7H] Automatic variable: _@KREG00 to 11 [0FED8H to 0FEE3H] _@KREG12 to 15 (not allocated to arguments) -QRV Declared argument or automatic variable HL register (only when base pointer is not required) Argument: _@KREG12 to 15 [0FEE4H to 0FEE7H] Automatic variable: _@KREG00 to 11 [0FED8H to 0FEE3H] _@KREG12 to 15 (not allocated to arguments) Default Declared argument, automatic variable Stack frame Order of appearance Only the number of bytes of the variable or argument is allocated based on the referenced count. Allocated to register as char type: L, H, in this order int, short, enum type: HL Priority Level char type: L, H, in this order int, short, enum type: HL
-QR (saddr allocation option)
register declared argument or automatic variable
Only the number of bytes of the variable or argument is allocated based on the referenced count. Allocated to register as char type: L, H, in this order int, short, enum type: HL
The following example shows the function call. (C source: Normal model at the -QRV specification)
void func0 (register int, int); void main(){ func0 (0x1234, 0x5678); } void func0 (register int p1, int p2){ register int r; int a; r=p2; a=p1; }
User's Manual U14872EJ1V0UM
471
CHAPTER 12
REFERENCING THE ASSEMBLER
(Output assembler source)
EXTRN EXTRN EXTRN EXTRN PUBLIC PUBLIC @@CODE _main: movw push movw call pop ret _func0: push xch xch xch xch push movw push movw push movw movw mov xch mov movw movw movw movw movw pop movw pop movw pop movw pop ret END
_@KREG12 _@KREG13 _@KREG10 _@KREG14 _func0 _main CSEG ax,#05678H ax ax,#01234H !_func0 ax ;22136 ;4660 ; Argument passed on stack ; 1st argument passed on register ; Function call ; Argument passed on stack
hl a,x a,_@KREG12 a,x a,_@KREG13 ax ax,_@KREG10 ax ax,_@KREG14 ax ax,sp hl,ax a,[hl+10] a,x a,[hl+11] hl,ax ax,hl _@KREG14,ax ax,_@KREG12 _@KREG10,ax ax _@KREG14,ax ax _@KREG10,ax ax _@KREG12,ax hl
; Saves the register for arguments
; Allocates register argument p1 to _@KREG12. ; Saves the saddr area for register arguments. ; Saves the saddr area for register variables. ; Saves the saddr area for automatic variables.
; Argument p2 passed on stack
;r ;p1 ;a
; Assigned to HL ; Argument p2 ; Assigned to register variables r. ; Register argument p1 ; Assigned to automatic variable a. ; Restores the saddr area for register variables. ; Restores the saddr area for automatic variables. ; Restores the saddr area for register arguments. ; Restores the register for arguments
472
User's Manual U14872EJ1V0UM
CHAPTER 12
REFERENCING THE ASSEMBLER
12.1.2 Static model * * On the function call side, register arguments are passed in the same way as regular arguments. Up to 3 arguments, or a total of 6 bytes, can be passed, all via a register. Table 12-3. Passing Arguments (Function Call Side)
Type 1-byte data 2-byte data 4-byte data Passing Location (First Argument) A AX Passing Location (Second Argument) B BC Passing Location (Third Argument) H HL
Allocated to AX and BC, remainder allocated to H or HL
Remark 1- to 4-byte data does not include structures and unions. * On the function definition side, arguments passed via a register are stored to the argument allocation location. Arguments (register arguments) declared with register are allocated to registers whenever possible, and regular arguments are allocated to areas reserved for specific functions. * * * All register arguments are passed via registers, but the registers on the function call side (passing side) and the function definition side (receiving side) differ, and therefore register copying is performed. Saving and restoring of registers to which arguments/automatic variables are allocated is performed on the function definition side. Function arguments and the values of automatic variables declared inside functions are stored in the function-specific areas listed below using an option. reserved for each function. Table 12-4. Storing of Arguments/Automatic Variables (Inside Called Function)
Option -QV (register allocation option) Argument/auto Variable Declared argument or automatic variable Storage Location DE register Priority Level Arguments: char type: D, E, in this order int, short, enum type: DE Automatic variables: char type: E, D, in this order int, short, enum type: DE Default Declared argument, automatic variable Function-specific area Arguments are allocated starting from the 1st argument, automatic variables are allocated by order of appearance Only the number of bytes of the variable or argument is allocated, according to the number of times referenced. Other than the number of bytes of the variable or argument is allocated to the area peculiar to the function.
Function-specific areas are static areas in RAM
Default
Argument, register variable declared with register
DE register
User's Manual U14872EJ1V0UM
473
CHAPTER 12
REFERENCING THE ASSEMBLER
The following example shows the function call. (C source: Static Model at -SM and -QV specifications)
void sub(); void func (register int, char); void main(){ func (0x1234, 0x56); } void func (register int p1, char p2){ register char r; int a; r=p2; a=p1; } sub();
(Output assembler source)
PUBLIC PUBLIC @@DATA ?L0005: ?L0006: ?L0007: @@CODE _main: mov movw call ret func: push movw movw mov mov movw mov xch mov call pop ret END
_func _main .. . DSEG DS (1) DS (1) DS (2) .. . CSEG b,#056H ax,#01234H !_func ;86 ;4660 ; Passes the 2nd argument by register B. ; Passes the 1st argument by register AX. ; Function call
; Argument p2 ; Register variable r ; Automatic variable a
de de,ax ax,bc !?L0005,a !?L0006,a ax,de !?L0007+1,a a,x !?L0007,a !_sub de
; Saves registers for register arguments. ; Allocates register arguments p1 to DE. ; Copies argument p2 to ?L0005. ; Assigned to register variable r ; Register argument p1
;r ;a ;a
; Assigned to automatic variable a ; Restores the register for register arguments.
474
User's Manual U14872EJ1V0UM
CHAPTER 12
REFERENCING THE ASSEMBLER
12.2 Storing Return Values
Return values during function calls are stored to registers and carry flags. The storage locations of return values are shown in the table below. Table 12-5. Storage Location of Return Values
Type 1-byte integer 2-byte integer 4-byte integer Pointer Structure, union BC (lower), DE (higher) BC BC (start address of structure or union copied to function-specific area) CY (carry flag) BC (low-order), DE (high-order) BC Normal Model A AX Not supported AX Not supported Static Model
1 bit Floating-point number
CY (carry flag) Not supported
User's Manual U14872EJ1V0UM
475
CHAPTER 12
REFERENCING THE ASSEMBLER
12.3 Calling Assembly Language Routines from C Language
This section shows examples when the normal model (default) is used. If the -QV option, -QR option, and -QRV option are specified, arguments are stored as indicated in Table 12-2. However, the HL register is allocated only when no base pointer is required (when base pointer is not used). Calling an assembly language routine from the C language is described as follows. * * C language function calling procedure Saving data from the assembly language routine and returning
(1) C language function calling procedure This is a C language program example that calls an assembly language routine. /* Function prototype */
extern int FUNC(int, long); void main() { int long
i, j; l;
i = 1; l = 0x54321; j = FUNC(i, l); }
/* Function call */
In this program example, the interface and control flow with the program that is being executed are as follows. (1) Placing the first argument passed from the main function to the FUNC function in the register, and the second and subsequent arguments on the stack. (2) Passing control to the FUNC function by using the CALL instruction. The next figure shows the stack immediately after control moves to the FUNC function in the above program example. Figure 12-1. Stack Area After a Call
low address
Stack pointer
Return address to main
l (lower word)
Arguments passed to the FUNC function AX register i
l (higher word)
high address Stack area
476
User's Manual U14872EJ1V0UM
CHAPTER 12
REFERENCING THE ASSEMBLER
(2) Saving data from the assembly language routine and returning The following processing is performed in the FUNC function called from the main function. (1) Save the base pointer, work register. (2) Copy the stack pointer (SP) to the base pointer (HL). (3) Perform the processing in the FUNC function. (4) Set the return value. (5) Restore the saved register. (6) Return to the main function. Next, an example of an assembly language program is explained.
$PROCESSOR(9024) PUBLIC _FUNC PUBLIC _DT1 PUBLIC _DT2 @@DATA ?DT1: ?DT2: @@CODE _FUNC: PUSH PUSH MOVW MOVW MOV MOV XCH MOV MOV MOV XCH MOV MOVW MOV XCH MOV MOVW HL AX AX,SP HL,AX A,[HL] !_DT1,A A,X A,[HL+1] !_DT1+1,A A,[HL+8] A,X A,[HL+9] BC,AX A,[HL+6] A,X A,[HL+7] DE,#_DT2 ; arg2 ; arg2 ; arg2 ; arg2 ; arg1 ; arg1 ; move 1st argument(i) ; Copies stack pointer ------------------------------- (2) ; Saves base pointer --------------------------------- (1) DS DS DSEG (2) (4) CSEG
User's Manual U14872EJ1V0UM
477
CHAPTER 12
REFERENCING THE ASSEMBLER
XCH MOV XCH INCW MOV XCHW INCW XCH MOV XCH INCW MOV XCHW MOVW POP POP END
A,X [DE],A A,X DE [DE],A AX,BC DE A,X [DE],A A,X DE [DE],A AX,BC BC,#0AH AX HL ; Restores base pointer----------------------------- (5) ; Sets return value------------------------------------ (4) ; Moves 2nd argument(l)
RET------------------------------------------------------------------------------------------------------------------------- (6)
478
User's Manual U14872EJ1V0UM
CHAPTER 12
REFERENCING THE ASSEMBLER
(1) Saving base pointer, work register A label with `_' prefixed to the function name described in the C source is described. Base pointers and work registers are saved with the same name as function names described inside the C source. After the label is described, the HL register (base pointer) is saved. In the case of programs generated by the C compiler, other functions are called without saving the register for register variables. Therefore, if changing the values of these registers for functions that are called, be sure to save the values beforehand. However, if register variables are not used on the calling side, saving the work register is not required. (2) Copying to base pointer (HL) of stack pointer (SP) The stack pointer (SP) changes due to `PUSH, POP' inside functions. Therefore, the stack pointer is copied to register `HL' and used as the base pointer of arguments. (3) Basic processing of FUNC function After the processing in (1) and (2) is performed, the basic processing of called functions is performed. (4) Setting the return value If there is a return value, it is set in the `BC' and `DE' registers. If there is no return value, setting is unnecessary. BC register Return value of 16 or fewer bits: Word DE register Return value of 17 or more bits: Higher word BC register Lower word
(5) Restoring the registers Restore the saved base pointer and work register. (6) Returning to the main function Figure 12-2. Stack Area After Returning
low address
Return address to main
Return value BC register
Stack pointer
l (lower word) Or
Word
AX register i high address
l (higher word) DE register Higher word Stack area BC register Lower word
User's Manual U14872EJ1V0UM
479
CHAPTER 12
REFERENCING THE ASSEMBLER
12.4 Calling C Language Routines from Assembly Language
(1) Calling the C language function from an assembly language program The procedure for calling a function written in the C language from an assembly language routine is: (1) Place the arguments on the stack. (2) Save the C work registers (AX, BC, and DE). (3) Call the C language function. (4) Increment the value of the stack pointer (SP) by the number of bytes of arguments. (5) Reference the return value of the C language function (in BC or DE and BC). This is an example of an assembly language program.
$PROCESSOR (9024) NAME EXTRN FUNC2 _CSUB
PUBLIC _FUNC2 @@CODE CSEG _FUNC2: movw push movw call pop ret END ax, #20H ax ax, #21H !_CSUB ax ; Sets 2nd argument (j) ; Sets 1st argument (i) ; Calls "CSUB (i, j)" ; ~ ;
(1) Stacking arguments Any arguments are placed on the stack. Figure 12-3 shows argument passing. Figure 12-3. Placing Arguments on Stack
low address CSUB (i, j) AX register 1st arg
2nd arg
high address Stack area
480
User's Manual U14872EJ1V0UM
CHAPTER 12
REFERENCING THE ASSEMBLER
(2) Saving the work registers (AX, BC, and DE) The three register pairs of AX, BC, and DE are used in the C language. Their values are not restored when returning. Therefore, if the values in registers are needed, they are saved on the calling side. Save or restore the registers before or after an argument pass code. The HL register is always saved on the side of the C language when it is used in the C language. (3) Calling a C language function A CALL instruction calls a C language function. If the C language function is a callt function, the callt instruction performs the call. (4) Restoring the stack pointer (SP) The stack pointer is restored by the number of bytes holding the arguments. (5) Referencing the return value (BC and DE) The return value from the C language is returned as follows. BC register Return value of 16 or fewer bits: Word DE register Return value of 17 or more bits: Higher word BC register Lower word
(2) Referencing arguments in a C language function To correctly pass the i and j arguments to the C language program shown below, they are placed on the stack as shown in Figure 12-4. void CSUB (i, j) int { i += j; } Figure 12-4. Passing Arguments to C Language
low address CSUB (i, j) Stack pointer Return address to the calling side AX register i j
i, j ;
high address Stack area
User's Manual U14872EJ1V0UM
481
CHAPTER 12
REFERENCING THE ASSEMBLER
12.5 Referencing Variables Defined in Other Languages
(1) Referencing variables defined in the C language If external variables defined in a C language program are referenced in an assembly language routine, the extern declaration is used. Underscores `_' are added to the beginning of the variables defined in the assembly language routine. C language program example
extern void subf(); char int { subf(); } c = 0; i = 0;
void main()
The following occurs in the RA78K0S assembler.
$PROCESSOR (9024) PUBLIC _subf EXTRN EXTRN @@CODE CSEG _subf: MOV MOV MOVW MOVW INCW MOV DECW XCH MOV RET END a, #04H !_c, a ax, #07H de, #_i DE [DE], A DE A, X [DE], A ;7 _c _i
482
User's Manual U14872EJ1V0UM
CHAPTER 12
REFERENCING THE ASSEMBLER
(2) Referencing variables defined in the assembly language from the C language Variables defined in assembly language are referenced from the C language in this way. C language program example
extern char c; extern int i; void subf() { c = 'A' ; i=4; }
The following occurs in the RA78K0S assembler.
NAME ASMSUB PUBLIC PUBLIC ABC _c: _i: CSEG DB DW END 0 0 _c _i
User's Manual U14872EJ1V0UM
483
CHAPTER 12
REFERENCING THE ASSEMBLER
12.6 Cautions
(1) `_' (underscore) This C compiler adds an underscore `_' (ASCII code `5FH') to external definitions and reference names of the object modules to be output. In the next C program example, "j = FUNC(i, l);" is taken as a reference to the external name _FUNC.
extern int FUNC(int, long); void main() { int long i = 1; l = 0x54321; j = FUNC(i, l); } i, j; l;
/* Function prototype */
/* Function call */
The routine name is written as `_FUNC' in RA78K0S. (2) Argument positions on the stack The arguments placed on the stack are placed from the postfix argument to the prefix argument in the direction from the high address to the low address. Figure 12-5. Stack Positions of Arguments
low address Return address to main j=FUNC(i, l); Stack pointer l (lower word) l (higher word) high address Stack area
AX register i
484
User's Manual U14872EJ1V0UM
CHAPTER 13
EFFECTIVE UTILIZATION OF COMPILER
This chapter introduces how to effectively use this C compiler.
13.1 Efficient Coding
When developing 78K/0S Series application products, efficient object generation may be realized with this C compiler by utilizing the saddr area or callt area of the device. * Use external variables if (saddr area is usable) sreg/_ _sreg variables are used/ compiler option (-RD) is used
* Use 1-bit data if (saddr area is usable) bit/boolean/ _ _boolean type variables are used
* Function definition if (function to be called several times) if (callt area is usable) Use as _ _callt/callt function (effective for reducing code size) if (not used recursively) Use as _ _leaf/norec function if (automatic variables are not used) Use as noauto function if (automatic variables are used &&saddr area is usable) register declaration
User's Manual U14872EJ1V0UM
485
CHAPTER 13
EFFECTIVE UTILIZATION OF COMPILER
(1) Using external variable When defining an external variable, specify the external variable to be defined as a sreg/_ _sreg variable if the saddr area can be used. Instructions to sreg/_ _sreg variables are shorter in code length than instructions to memory. This helps shorten object code and improve program execution speed. (The same can be also performed by specifying the -RD option, instead of using the sreg variable.) Definition of sreg/_ _sreg variable: extern sreg int variable-name ; extern_ _sreg int variable-name ;
Remark (2) 1-bit data
Refer to 11.5 (3) How to use the saddr area.
A data object which only uses 1-bit data should be declared as a bit type variable (or boolean/_ _boolean type variable). A bit manipulation instruction will be generated for an operation on bit/boolean/_ _boolean type variables. Because the saddr area is used as well as the sreg variable, the codes can be shortened and the execution speed can be improved. Declaration of bit/boolean type variable: bit variable-name ; boolean variable-name ; _ _boolean variable-name ;
Remark
Refer to 11.5 (7) bit type variables.
(3) Function definitions For a function to be called repeatedly, object code should be shortened or a structure that allows calling at high speeds should be provided. If the callt area can be used for functions to be called frequently, such functions should be defined as callt functions. The callt function can be called faster than ordinary function calls with a shorter code because the callt function is called using the callt area of the device. Definition of callt function: callt int tsub() { . . . } Remark Refer to 11.5 (1) callt functions and 11.5 (6) norec function.
In addition to the use of the saddr area, objects that do not require modification of the C source by compiling with optimization options can be generated. For the effect of each -Q suboption, refer to the
CC78K0S C Compiler Operation (U14871E).
486
User's Manual U14872EJ1V0UM
CHAPTER 13
EFFECTIVE UTILIZATION OF COMPILER
(4) Optimization options The optimization option that emphasizes the object code size the most is as follows. [Object code is emphasized the most] -QX3
The further shortening of the code size and the improvement of the execution speed is possible by adding _ _sreg to variables. However, this is restricted to cases when the saddr area can be used. If there is insufficient area and the saddr area cannot be used, a compile error occurs. To highly emphasize the execution speed, specify the -QX2 default. In addition, the object efficiency can be improved by adding the extended functions supported by this compiler to the C source. (5) Using extended description
* Function definition if (function to be called several times) if (not used recursively) Use as _ _leaf/norec function if (automatic variables not used) Use as noauto function if (automatic variables are used && register/saddr area is usable) register declaration if (internal static variables are used) && (saddr area is usable) _ _sreg declaration * Functions not used recursively Of the functions to be called repeatedly, the ones which are not used recursively should be defined as _ _leaf/norec functions. The norec function is a function that does not have preprocessing/ postprocessing (stack frame). Therefore, the object code can be shortened and the execution speed can be improved compared to ordinary functions. Remark For the definition of the norec function (norec int rout ()...), refer to 11.5 (6) norec function and 11.7.4 norec function call interface.
User's Manual U14872EJ1V0UM
487
CHAPTER 13
EFFECTIVE UTILIZATION OF COMPILER
* Functions that do not use automatic variables Functions that do not use automatic variables should be defined as a noauto function. This function does not output code for stack frame formation and its arguments are passed to registers as much as possible, which helps shorten object code and improve program execution speed. Remark Refer to 11.5 (5) noauto function, 11.7.3 noauto function call interface about noauto
function definition (noauto int sub1 (int i) ...). * Functions that use automatic variables If the saddr area can be used for a function that does not use automatic variables, declare the function with the register storage class specifier. By this register declaration, the declared object will be allocated to a register. A program using registers operates faster than one using memory, and object code can be shortened as well. Remark Refer to 11.5 (2) Register variables for the definition of register variables (register int i; ...).
* Functions that use internal static variables If the saddr area can be used for a function that uses internal static variables, declare the function with _ _sreg or specify the -RS option. In the same way as with sreg variables, the object code can be shortened and the execution speed can be improved. Remark Refer to 11.5 (3) How to use the saddr area.
In addition, the code efficiency and the execution speed can be improved by the following method. * Use of SFR name (or SFR bit name). #pragma sfr * Use of _ _sreg declaration for bit fields which consist only of 1-bit members (unsigned char type can be used for members). _ _sreg struct bf { unsigned char a : 1 ; unsigned char b : 1 ; unsigned char c : 1 ; unsigned char d : 1 ; unsigned char e : 1 ; unsigned char f : 1 ; } bf_1 ; * Use of multiplication and division embedded function. #pragma mul #pragma div * Description of only the modules whose speed needs to be improved in the assembly language.
488
User's Manual U14872EJ1V0UM
APPENDIX A
LIST OF LABELS FOR saddr AREA
In the CC78K0S, the saddr area is referenced by the following label names. Therefore, labels in the C source program and in assembler source program that have the same names as the following labels cannot be used.
A.1 Normal Model
(a) Register variables
Label Name _@KREG00 _@KREG01 _@KREG02 _@KREG03 _@KREG04 _@KREG05 _@KREG06 _@KREG07 _@KREG08 _@KREG09 _@KREG10 _@KREG11 _@KREG12 _@KREG13 _@KREG14 _@KREG15 0FED8H 0FED9H 0FEDAH 0FEDBH 0FEDCH 0FEDDH 0FEDEH 0FEDFH 0FEE0H 0FEE1H 0FEE2H 0FEE3H 0FEE4HNote 0FEE5HNote 0FEE6HNote 0FEE7HNote Address
Note When the arguments of the function are declared by register or the -QV option is specified and the -QR option is specified, arguments are allocated to the saddr area. (b) Arguments of norec function
Label Name _@NRARG0 _@NRARG1 _@NRARG2 _@NRARG3 0FEE8H 0FEEAH 0FEECH 0FEEEH Address
User's Manual U14872EJ1V0UM
489
APPENDIX A
LIST OF LABELS FOR saddr AREA
(c) Automatic variables of norec function
Label Name _@NRAT00 _@NRAT01 _@NRAT02 _@NRAT03 _@NRAT04 _@NRAT05 _@NRAT06 _@NRAT07 0FEF0H 0FEF1H 0FEF2H 0FEF3H 0FEF4H 0FEF5H 0FEF6H 0FEF7H
Address
(d) Arguments of runtime library
Label Name _@RTARG0 _@RTARG1 _@RTARG2 _@RTARG3 _@RTARG4 _@RTARG5 _@RTARG6 _@RTARG7 0FEF8H 0FEF9H 0FEFAH 0FEFBH 0FEFCH 0FEFDH 0FEFEH 0FEFFH Address
490
User's Manual U14872EJ1V0UM
APPENDIX A
LIST OF LABELS FOR saddr AREA
A.2 Static Model
(a) Shared area
Label Name _@KREG00 _@KREG01 _@KREG02 _@KREG03 _@KREG04 _@KREG05 _@KREG06 _@KREG07 _@KREG08 _@KREG09 _@KREG10 _@KREG11 _@KREG12 _@KREG13 _@KREG14 _@KREG15 0FEF0H 0FEF1H 0FEF2H 0FEF3H 0FEF4H 0FEF5H 0FEF6H 0FEF7H 0FEF8H 0FEF9H 0FEFAH 0FEFBH 0FEFCH 0FEFDH 0FEFEH 0FEFFH Address
(b) For arguments, automatic variables, and work
Label Name _@NRAT00 _@NRAT01 _@NRAT02 _@NRAT03 _@NRAT04 _@NRAT05 _@NRAT06 _@NRAT07 0FExxH
Note
Address
_@NRAT00 + 1 _@NRAT00 + 2 _@NRAT00 + 3 _@NRAT00 + 4 _@NRAT00 + 5 _@NRAT00 + 6 _@NRAT00 + 7
Note Arbitrary address in the saddr area
User's Manual U14872EJ1V0UM
491
APPENDIX B
LIST OF SEGMENT NAMES
This chapter explains all the segments that the compiler outputs and their locations. (1) and (2) show the option and re-allocation attributes used in the table. This section describes all the segments that are output by the compiler. <1> CSEG re-allocation attribute CALLT0: Allocates the specified segment so that the start address is a multiple of two within the range of 40H to 7FH. AT absolute expression: Allocates the specified segment to an absolute address (within the range of 0000H to FEFFH). FIXED: UNITP: Allocates the start address of the specified segment within the range of 800H to 0FFFH. Allocates the specified segment so that the start address is a multiple of two within any position (within the range of 80H to 0FA7EH). <2> DSEG re-allocation attribute SADDRP: UNITP: Allocates the specified segment so that the start address is a multiple of two within the range of FE20H to FEFFH in the saddr area. Allocates the specified segment so that the start address is a multiple of two within any position (default is within the RAM area).
492
User's Manual U14872EJ1V0UM
APPENDIX B
LIST OF SEGMENT NAMES
B.1 List of Segment Names
Section Name @@CODE @@CNST @@R_INIT @@R_INIS @@CALT @@VECTnn @@INIT @@DATA @@INIS @@DATS @@BITS Segment Type CSEG CSEG CSEG CSEG CSEG CSEG DSEG DSEG DSEG DSEG BSEG SADDRP SADDRP UNITP CALLT0 AT 00nnH Re-allocation Attribute Segment for code portion Segment for const variable Segment for initialization data (with initial value) Segment for initialization data (sreg variable with initial value) Segment for callt function table Segment for vector tableNote Segment for data area (with initial value) Segment for data area (without initial value) Segment for data area (sreg variable with initial value) Segment for data area (sreg variable without initial value) Segment for boolean-type and bit-type variables Description
Note The value of nn changes depending on the interrupt types.
B.2 Location of Segment
Segment Type CSEG BSEG DSEG ROM saddr area of RAM RAM Destination of Allocation (Default)
User's Manual U14872EJ1V0UM
493
APPENDIX B
LIST OF SEGMENT NAMES
B.3 Example of C Source
#pragma INTERRUPT INTP0 inter void inter (void) ; const int i_cnst = 1 ; callt void f_clt (void) ; boolean b_bit ; long l_init = 2 ; int i_data ; sreg int sr_inis = 3 ; sreg int sr_dats ; void main () { int i ; i = 100 ; } void inter () { unsigned char uc = 0; uc++; if (b_bit) b_bit = 0 ; } callt void f_clt () { } /* callt function definition */ /* Interrupt function definition */ /* Interrupt vector */
/* Interrupt function prototype declaration */ /* const variable /* callt function prototype declaration /* boolean-type variable /* External variable with initial value /* External variable without initial value /* sreg variable with initial value /* sreg variable without initial value /* Function definition */ */ */ */ */ */ */ */
494
User's Manual U14872EJ1V0UM
APPENDIX B
LIST OF SEGMENT NAMES
B.4 Example of Output Assembler Module
Quasi-directives and instruction sets in an assembler source vary depending on the device. Refer to the RA78K0S Online Help for details. ; 78K/0S Series C Compiler V1.30 Assembler Source ; ; Command ; In-file ; Asm-file : -c9026 sampk0s.c -sa -ng : sampk0s.c : sampk0s.asm Date:xx xxx xxxx Time:xx:xx:xx
; Para-file : $PROCESSOR(9026) $NODEBUG $NODEBUGA $KANJICODE SJIS $TOL_INF EXTRN PUBLIC PUBLIC PUBLIC PUBLIC PUBLIC PUBLIC PUBLIC PUBLIC PUBLIC PUBLIC PUBLIC @@BITS _b_bit @@CNST _i_cnst: @@R_INIT DW @@INIT DSEG DS (4) ; Segment for data area (external variables without an initial value)
User's Manual U14872EJ1V0UM
03FH, 0130H, 00H, 00H _@cprep _inter ?f_clt _i_cnst _b_bit _l_init _i_data _sr_inis _sr_dats _main _f_clt _@vect06 ; Segment for boolean-type variables
BSEG DBIT CSEG DW CSEG 00002H,00000H ; 2 01H ;1
; Segment for const variables
; Segment for initialization data (external variables with an initial value)
; Segment for data area (external variables with an initial value)
_l_init: @@DATA DSEG
495
APPENDIX B
LIST OF SEGMENT NAMES
_i_data: @@R_INIS DW @@INIS DSEG
DS CSEG 03H SADDRP DS SADDRP DS CALLT0 _f_clt
(2) UNITP ;3 ; Segment for data area (sreg variables with an initial value) (2) ; Segment for data area (sreg variables without an initial value) (2) ; Segment for the callt function ; Segment for initialization data (sreg variables with an initial value)
_sr_inis: @@DATS DSEG
_sr_dats: @@CALT CSEG
?f_clt: DW ; line ; line ; line ; line ; line ; line ; line ; line ; line ; line ; line ; line ; line @@CODE _main: push movw callt ; line ; line 14 : 15 : movw mov xch mov ; line pop pop ret ; line ; line 17 :
1 : #pragma INTERRUPT INTP0 inter 2: 3 : void inter(void); 4 : const int i_cnst=1; 5 : callt void f_clt(void); 6 : boolean b_bit; 7 : long l_init=2; 8 : int i_data; 9 : sreg int sr_inis=3; 10 : sreg int sr_dats; 11 : 12 : void main() 13 : { CSEG hl ax,#02H [_@cprep] int i=100; ax,#064H [hl+1],a a,x [hl],a ; i ax hl ; 100 ;i i;
/*Interrupt vector*/ /*Interrupt function prototype declaration*/ /*const variable*/ /*callt function prototype declaration*/ /*boolean-type variable*/ /*External variable with an initial value*/ /*External variable without an initial value*/ /*sreg variable with an initial value */ /*sreg variable without an initial value */ /*Function definition*/
; Segment for code block ;[INF] 1, 4 ;[INF] 3, 6 ;[INF] 1, 8
;[INF] 3, 6 ;[INF] 2, 6 ;[INF] 1, 4 ;[INF] 1, 6 ;[INF] 1, 6 ;[INF] 1, 6 ;[INF] 1, 6 /*Interrupt function definition*/
16 : }
18 : void inter()
User's Manual U14872EJ1V0UM
496
APPENDIX B
LIST OF SEGMENT NAMES
; line _inter:
19 : { push push push movw callt ax de hl ax,#02H [_@cprep] unsigned char uc=0; a,a [hl+1],a uc++; a a,[hl+1] if(b_bit) _b_bit,$L0005 23 : clr1 b_bit=0; _b_bit ;[INF] 3, 6 ;[INF] 4,10 ; uc ;[INF] 2, 4 ;[INF] 2, 8 ; uc ;[INF] 2, 4 ;[INF] 2, 6 ;[INF] 1, 4 ;[INF] 1, 4 ;[INF] 1, 4 ;[INF] 3, 6 ;[INF] 1, 8
; line
20 : xor mov
; line
21 : inc xch
; line bf ; line L0005: ; line
22 :
24 : } pop pop pop pop reti ax hl de ax ;[INF] 1, 6 ;[INF] 1, 6 ;[INF] 1, 6 ;[INF] 1, 6 ;[INF] 1, 8 /*callt function definition */
; line ; line ; line _f_clt: ; line
25 : 26 : callt void f_clt() 27 : { 28 : } ret ;[INF] 1, 6 CSEG _inter AT 0006H ; Interrupt vector
@@VECT06 _@vect06: DW END
; *** Code Information *** ; ; $FILE C:\NECTools32\work\sampk0s.c ; ; $FUNC main(13) ; ; ; ; $FUNC inter(19) ; ; void=(void) CODE SIZE= 27 bytes, CLOCK_SIZE= 96 clocks, STACK_SIZE= 10 bytes
User's Manual U14872EJ1V0UM
void=(void) CODE SIZE= 15 bytes, CLOCK_SIZE= 58 clocks, STACK_SIZE= 6 bytes
497
APPENDIX B
LIST OF SEGMENT NAMES
; ; $FUNC f_clt(27) ; ; void=(void) CODE SIZE= 1 bytes, CLOCK_SIZE= 6 clocks, STACK_SIZE= 0 bytes
; Target chip : uPD78926 ; Device file : Vx.xx
498
User's Manual U14872EJ1V0UM
APPENDIX C
LIST OF RUNTIME LIBRARIES
Table C-1 shows the runtime library list. These operational instructions are called in the format where @@, etc. are attached at the beginning of the function name. However, cstart, cprep, and cdisp are called in the format with _@ attached to the beginning. No library support is available for operations not in Table C-1. The compiler executes inline expansion. long addition and subtraction, and/or/xor and shift may be expanded inline. Table C-1. List of Runtime Libraries (1/6)
Classification Function Name lsinc luinc finc Decrement lsdec ludec fdec Sign reverse lsrev lurev frev 1's complement lscom lucom Logical NOT lsnot lunot fnot Multiply csmul cumul ismul iumul lsmul lumul fmul Divide csdiv cudiv isdiv iudiv lsdiv ludiv fdiv Supported Model Normal Model Static Model - - - - - - - - - - - - - - - - - - - - Increments signed long Increments unsigned long Increments float Decrements signed long Decrements unsigned long Decrements float Reverses the sign of signed long Reverses the sign of unsigned long Reverses the sign of float Obtains 1's complement of signed long Obtains 1's complement of unsigned long Negates signed long Negates unsigned long Negates float Performs multiplication between signed char data Performs multiplication between unsigned char data Performs multiplication between signed int data Performs multiplication between unsigned int data Performs multiplication between signed long data Performs multiplication between unsigned long data Performs multiplication between float data Performs division between signed char data Performs division between unsigned char data Performs division between signed int data Performs division between unsigned int data Performs division between signed long data Performs division between unsigned long data Performs division between float data Function
Increment
User's Manual U14872EJ1V0UM
499
APPENDIX C
LIST OF RUNTIME LIBRARIES
Table C-1. List of Runtime Libraries (2/6)
Classification Function Name csrem curem isrem iurem lsrem lurem Add lsadd luadd fadd Subtract lssub lusub fsub Shift left islsh iulsh lslsh lulsh Shift right isrsh iursh lsrsh lursh Compare cscmp iscmp lscmp lucmp fcmp Bit AND lsband luband Bit OR lsbor lubor Bit XOR lsbxor lubxor Logical AND Logical OR Conversion from floating-point number Conversion to floating-point number Conversion from bit fand for ftols ftolu lstof lutof btol Supported Model Normal Model Static Model - - - - - - - - - - - - - - - - - - - - - - - - - - - - Obtains remainder after division between signed char data Obtains remainder after division between unsigned char data Obtains remainder after division between signed int data Obtains remainder after division between unsigned int data Obtains remainder after division between signed long data Obtains remainder after division between unsigned long data Performs addition between signed long data Performs addition between unsigned long data Performs addition between float data Performs subtraction between signed long data Performs subtraction between unsigned long data Performs subtraction between float data Shifts signed int data to the left Shifts unsigned int data to the left Shifts singed long data to the left Shifts unsigned long data to the left Shifts signed int data to the right Shifts unsigned int data to the right Shifts signed long data to the right Shifts unsigned long data to the right Compares signed char data Compares signed int data Compares signed long data Compares unsigned long data Compares float data Performs an AND operation between signed long data Performs an AND operation between unsigned long data Performs an OR operation between signed long data Performs an OR operation between unsigned long data Performs an XOR operation between signed long data Performs an XOR operation between unsigned long data Performs a logical AND operation between two float data Performs a logical OR operation between two float data Converts from float to signed long Converts from float to unsigned long Converts from signed long to float Converts from unsigned long to float Converts from bit to long Function
Remainder
500
User's Manual U14872EJ1V0UM
APPENDIX C
LIST OF RUNTIME LIBRARIES
Table C-1. List of Runtime Libraries (3/6)
Classification Function Name cstart Supported Model Normal Model Static Model Startup module * After an area (2 x 32 bytes) where a function that will be registered is reserved with the atexit function, sets the beginning label name to _@FNCTBL. * Reserve a break area (32 bytes), sets the beginning label name to _@MEMTOP, and then sets the next label name of the area to _@MEMBTM. * Define the segment in the reset vector table as follows, and set the beginning address of the startup module. @@VECT00 CSEG DW input. * Set the variable _@FNCENT, to which the number of functions registered by the atexit function is input, to 0. * Set the address of _@MEMTOP to the variable _@BRKADR as the initial break value. * Set 1 as the initial value for the variable _@SEED, which is the source of pseudo random numbers for the rand function. * Perform copy processing of initialized data and execute 0 clear of external data without an initial value. * Call the main function (user program) * Call the exit function by parameter 0. Pre- and postprocessing of function cprep cdisp cprep2 cdisp2 nrcp2 nrcp3 krcp2 krcp3 nkrc3 nrip2 nrip3 krip2 krip3 nkri31 nkri32 nrsave nrload - - - - - - - - - - - - - - - - - For saving _@NRATxx For restoring _@NRATxx Preprocessing of function Postprocessing of function Preprocessing of function (including the saddr area for register variables) Postprocessing of function (including the saddr area for register variables) For copying arguments AT 0000H _@cstart Function
Startup routine
* Set 0 to the variable _errno to which the error number is
User's Manual U14872EJ1V0UM
501
APPENDIX C
LIST OF RUNTIME LIBRARIES
Table C-1. List of Runtime Libraries (4/6)
Classification Function Name krs02 krs04 krs04i krs06 krs06i krs08 krs08i krs10 krs10i krs12 krs12i krs14 krs14i krs16 krs16i krl02 krl04 krl04i krl06 krl06i krl08 krl08i krl10 krl10i krl12 krl12i krl14 krl14i krl16 krl16i hdwinit BCD-type conversion bcdtob btobcd bcdtow wtobcd bbcd Auxiliary mulu divuw Supported Model Normal Model - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Static Model Performs initialization processing of peripheral devices (sfr) immediately after CPU reset. Converts 1-byte bcd to 1-byte binary Converts 1-byte binary to 2-byte bcd Converts 2-byte bcd to 2-byte binary Converts 2-byte binary to 2-byte bcd Converts 1-byte binary to 1-byte bcd K0mulu instruction-compatible K0divuw instruction-compatible For restoring _@KREGxx For saving _@KREGxx Function
Pre- and postprocessing of function
502
User's Manual U14872EJ1V0UM
APPENDIX C
LIST OF RUNTIME LIBRARIES
Table C-1. List of Runtime Libraries (5/6)
Classification Function Name clra0 clra1 clrax0 clrax1 clrbc0 clrbc1 cmpa0 cmpa1 cmpc0 cmpax0 cmpax1 movca movac ctoi uctoi adjba adjbs addrde addrhl shl4 shr4 tabled tableh apdecd apdech apincd apinch deilo deist deiinc deidec hlilo hlist hliinc hlidec dellab dell03 della4 delsab dels03 Supported Model Normal Model Static Model - - - - - For replacing the fixed-type instruction pattern Function
Auxiliary
User's Manual U14872EJ1V0UM
503
APPENDIX C
LIST OF RUNTIME LIBRARIES
Table C-1. List of Runtime Libraries (6/6)
Classification Function Name hlllab hlll03 hllla4 hllsab hlls03 hliadd hlisub hlicmp hliand hlior hlixor imule isdive iudive isreme iureme iadde isube iande iore ixore Supported Model Normal Model
Function
Static Model - - - - -
Auxiliary
For replacing the fixed-type instruction pattern


504
User's Manual U14872EJ1V0UM
APPENDIX D
LIST OF LIBRARY STACK CONSUMPTION
Table D-1 shows the number of stacks consumed from the standard libraries. Table D-1. List of Standard Library Stack Consumption (1/4)
Classification ctype.h Function Name isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper isascii toascii _tolower _toupper tolow toup setjmp.h setjmp longjmp stdarg.h va_arg va_start va_end stdio.h sprintf sscanf printf scanf vprintf vsprintf getchar gets putchar puts stdlib.h atoi atol strtol 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 2 0 0 0 52 (72)
Note 1 Note 1
Normal Model 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 2 -- -- -- -- -- -- -- -- -- 0 6 0 4 4 -- --
Static Model
290 (304)
54 (72)Note 1 294 (304) 52 (72)
Note 1 Note 1
52 (72)Note 1 0 6 0 4 4 10 20
User's Manual U14872EJ1V0UM
505
APPENDIX D
LIST OF LIBRARY STACK CONSUMPTION
Table D-1. List of Standard Library Stack Consumption (2/4)
Classification stdlib.h Function Name strtoul calloc free malloc realloc abort atexit exit abs div labs ldiv brk sbrk atof strtod itoa ltoa ultoa rand srand bsearch qsort strbrk strsbrk stritoa strltoa strultoa string.h memcpy memmove strcpy strncpy strcat strncat memcmp strcmp strncmp memchr strchr strcspn strpbrk 20 14 8 6 12 0 0 2+n 0 6 2 16 0 4 33 33 10 16 16 16 0 32 + nNote 3 16 + n 0 4 10 16 16 4 4 2 4 2 4 2 2 2 2 2 6 4
Note 4 Note 2
Normal Model -- 14 8 6 12 0 0 2 + nNote 2 0 -- -- -- 0 4 -- -- 10 -- -- -- -- -- -- 0 4 10 -- -- 6 8 4 6 4 6 4 2 4 2 0 6 4
Static Model
506
User's Manual U14872EJ1V0UM
APPENDIX D
LIST OF LIBRARY STACK CONSUMPTION
Table D-1. List of Standard Library Stack Consumption (3/4)
Classification string.h Function Name strrchr strspn strstr strtok memset strerror strlen strcoll strxfrm math.h acos asin atan atan2 cos sin tan cosh sinh tanh exp frexp ldexp log log10 modf pow sqrt ceil fabs floor frmod matherr acosf asinf atanf atan2f cosf sinf tanf coshf sinhf 4 6 4 4 4 0 0 2 4 24 24 20 21 24 (34)
Note 5
Normal Model 4 6 4 4 4 0 0 2 4 -- -- -- -- -- -- -- -- -- -- --
Note 5
Static Model
24 (34)Note 5 26 (34) 24 25 30 22 2 (10) 2 (10)Note 5 24 (34) 24 (34)
Note 5 Note 5 Note 5
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
2 (10)Note 5 25 (35) 18 2 0 2 2 (10)Note 5 0 24 24 20 21 24 (34)
Note 5 Note 5
-- -- -- -- --
24 (34)Note 5 26 (34) 24 25
Note 5
User's Manual U14872EJ1V0UM
507
APPENDIX D
LIST OF LIBRARY STACK CONSUMPTION
Table D-1. List of Standard Library Stack Consumption (4/4)
Classification math.h Function Name tanhf expf frexpf ldexpf logf log10f modff powf sqrtf ceilf fabsf floorf fmodf assert.h _ _assertfail 30 22 2 (10)Note 5 2 (10)
Note 5
Normal Model -- -- -- -- -- -- -- -- -- -- -- -- -- --
Note 6
Static Model
24 (34)Note 5 24 (34)Note 5 2 (10)
Note 5 Note 5
25 (35) 18 2 0 2
2 (10)Note 5 66 (84)
Notes 1. Values in parentheses are for when a version that supports floating-point numbers is used. 2. n is the total stack consumption among external functions registered by the atexit function. 3. n is the stack consumption of external functions called from bsearch. 4. n is (20 + stack consumption of external functions called from qsort) x (1 + number of times recursive calls occurred). 5. Values in parentheses are for when an operation exception occurs. 6. Values in parentheses are for when the printf version that supports floating-point numbers is used.
508
User's Manual U14872EJ1V0UM
APPENDIX D
LIST OF LIBRARY STACK CONSUMPTION
Table D-2 shows the number of stacks consumed from the runtime libraries. Table D-2. List of Runtime Library Stack Consumption (1/5)
Classification Increment Function Name lsinc luinc finc Decrement lsdec ludec fdec Sign reverse lsrev lurev frev 1's complement lscom lucom Logical NOT lsnot lunot fnot Multiply csmul cumul ismul iumul lsmul lumul fmul Divide csdiv cudiv isdiv iudiv lsdiv ludiv fdiv Remainder csrem curem isrem iurem lsrem lurem Add lsadd luadd fadd Subtract lssub lusub fsub 0 0 12 (22) 0 0 12 (22) 0 0 0 0 0 0 0 0 4 4 6 6 6 6 8 (18) 8 4 8 4 10 6 8 (18) 8 4 8 4 10 6 0 0 8 (18) 0 0 8 (18)
Note 1 Note 1 Note 1 Note 1 Note 1 Note 1
Normal Model -- -- -- -- -- -- -- -- -- -- -- -- -- -- 4 4 6 6 -- -- -- 8 4 12 6 -- -- -- 8 4 12 6 -- -- -- -- -- -- -- --
Static Model
User's Manual U14872EJ1V0UM
509
APPENDIX D
LIST OF LIBRARY STACK CONSUMPTION
Table D-2. List of Runtime Library Stack Consumption (2/5)
Classification Shift left Function Name islsh iulsh lslsh lulsh Shift right isrsh iursh lsrsh lursh Compare cscmp iscmp lscmp lucmp fcmp Bit AND Bit OR Bit XOR Logical AND Logical OR Conversion from floating-point number Conversion to floating-point number Conversion from bit Startup routine Pre- and postprocessing of function lsband luband lsbor lubor lsbxor lubxor fand for ftols ftolu lstof lutof btol cstart cprep cdisp cprep2 cdisp2 nrcp2 nrcp3 krcp2 krcp3 nkrc3 nrip2 nrip3 krip2 krip3 nkri31 nkri32 nrsave nrload 0 0 2 2 0 0 2 2 0 0 2 2 4 (14)Note 1 0 0 0 0 0 0 0 0 4 4 12 (22)Note 1 12 (22)Note 1 0 2 2+n 0 Size of automatic variable + register variable 0 -- -- -- -- -- -- -- -- -- -- -- -- --
Note 2
Normal Model 0 0 -- -- 0 0 -- -- 2 2 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 2 -- -- -- -- 0 0 0 0 0 0 0 0 0 0 0 8 0
Static Model
510
User's Manual U14872EJ1V0UM
APPENDIX D
LIST OF LIBRARY STACK CONSUMPTION
Table D-2. List of Runtime Library Stack Consumption (3/5)
Classification Pre- and postprocessing of function Function Name krs02 krs04 krs04i krs06 krs06i krs08 krs08i krs10 krs10i krs12 krs12i krs14 krs14i krs16 krs16i krl02 krl04 krl04i krl06 krl06i krl08 krl08i krl10 krl10i krl12 krl12i krl14 krl14i krl16 krl16i hdwinit BCD-type conversion bcdtob btobcd bcdtow wtobcd bbcd Auxiliary mulu divuw -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 0 4 8 4 10 8 4 6 Normal Model 2 4 4 6 6 8 8 10 10 12 12 14 14 16 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 8 4 10 8 4 6 Static Model
User's Manual U14872EJ1V0UM
511
APPENDIX D
LIST OF LIBRARY STACK CONSUMPTION
Table D-2. List of Runtime Library Stack Consumption (4/5)
Classification Auxiliary Function Name clra0 clra1 clrax0 clrax1 clrbc0 clrbc1 cmpa0 cmpa1 cmpc0 cmpax0 cmpax1 movca movac ctoi uctoi adjba adjbs addrde addrhl shl4 shr4 tabled tableh apdecd apdech apincd apinch deilo deist deiinc deidec hlilo hlist hliinc hlidec dellab dell03 della4 delsab dels03 hlllab hlll03 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 2 0 0 Normal Model 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -- -- -- -- -- -- -- Static Model
512
User's Manual U14872EJ1V0UM
APPENDIX D
LIST OF LIBRARY STACK CONSUMPTION
Table D-2. List of Runtime Library Stack Consumption (5/5)
Classification Auxiliary Function Name hllla4 hllsab hlls03 hliadd hlisub hlicmp hliand hlior hlixor imule isdive iudive isreme iureme iadde isube iande iore ixore 0 0 0 0 0 0 0 0 0 10 12 8 12 8 0 2 0 0 0 Normal Model -- -- -- 0 0 0 0 0 0 10 16 10 16 10 0 2 0 0 0 Static Model
Notes 1. Values in parentheses are for when an operation exception occurs (when the matherr function included with the compiler is used). 2. n is the size of the automatic variable to be secured.
User's Manual U14872EJ1V0UM
513
APPENDIX E INDEX
\a .............................................................................. 36 \b ............................................................................. 36 \f ............................................................................. 36 \n ............................................................................. 36 \r ............................................................................. 36 \t ............................................................................. 36 \v ............................................................................. 36 #asm - #endasm .................................................... 339 #define directive..................................................... 155 #include.................................................................... 52 #include directive ................................................... 150 # operator............................................................... 153 ## operator............................................................. 153 #pragma access..................................................... 356 #pragma asm ......................................................... 339 #pragma bcd .......................................................... 390 #pragma di ............................................................. 351 #pragma directive .................................................. 306 #pragma div ........................................................... 387 #pragma ei ............................................................. 351 #pragma halt .......................................................... 354 #pragma inline ....................................................... 415 #pragma interrupt................................................... 342 #pragma mul .......................................................... 385 #pragma name....................................................... 381 #pragma nop.......................................................... 354 #pragma opc .......................................................... 394 #pragma realregister.............................................. 411 #pragma rot............................................................ 382 #pragma section .................................................... 368 #pragma sfr............................................................ 323 #pragma stop ......................................................... 354 #pragma vect ......................................................... 342 _ _asm ................................................................... 339 _ _assertfail............................................................ 295 _ _boolean ............................................................. 335 _ _callt .................................................................... 309 _ _DATE_ _............................................................ 161 _ _FILE_ _ ............................................................. 161 _ _interrupt............................................................. 349 _ _LINE_ _ ............................................................. 161 _ _OPC .................................................................. 394 _ _pascal.................................................................. 37 _ _STDC_ _ ........................................................... 161 _ _TIME_ _............................................................. 161
_toupper .................................................................190 ?? .............................................................................36 -QL option...............................................................310 -ZR option...............................................................405
A
abort .......................................................................220 abs..........................................................................222 Absolute address access function....................31, 356 Absolute address allocation specification.........33, 418 acos........................................................................250 acosf.......................................................................273 Aggregate type .........................................................46 ANSI .......................................................................300 Arithmetic operators .................................................90 Arrangement offset calculation simplification method ......................................................................33, 409 Array .......................................................................133 Array declarator ........................................................63 Array type .................................................................47 asin.........................................................................251 asinf........................................................................274 ASM statements ...............................................31, 339 Assembly language ..................................................21 assert......................................................................185 Assignment operators ............................................107 atan ........................................................................252 atan2 ......................................................................253 atan2f .....................................................................276 atanf .......................................................................275 atexit ...............................................................185, 221 atof .................................................................185, 225 atoi..........................................................................211 atol..........................................................................211 auto ..........................................................................54 Automatic pascal functionization of function call interface ........................................................32, 405
B
BCD operation function ....................................32, 390 Binary constant.................................................32, 379 Bit field....................................................................360 Bit field declaration ...........................................31, 360 bit type variables...............................................31, 335
514
User's Manual U14872EJ1V0UM
APPENDIX E
INDEX
Bitwise AND operator............................................. 100 Bitwise inclusive OR operator ................................ 102 Bitwise XOR operator ............................................ 101 Block scope ............................................................. 40 boolean type variables..................................... 31, 335 Branch statement................................................... 112 break statement ..................................................... 129 brk.................................................................. 185, 224 bsearch .................................................................. 229
do statement ..........................................................124
E
EI............................................................................351 Enumeration constant ..............................................50 Enumeration type .....................................................43 Enumeration type specifier.......................................59 Equality operators ....................................................98 errno.......................................................................178 error........................................................................178 ESCAPE sequence ..................................................36 exit..................................................................185, 221 exp..........................................................................260 expf.........................................................................283 Expression statement.............................................112 extern .......................................................................54 External definition...................................................137 External linkage........................................................40 External object definitions ......................................140
C
C language .............................................................. 21 calloc...................................................................... 216 callt functions ................................................... 30, 309 Cast operator ........................................................... 89 ceil ......................................................................... 268 ceilf ........................................................................ 291 Changing compiler output section name ............... 368 char type .................................................................. 42 Character constant .................................................. 51 Character type ......................................................... 46 Comma operator.................................................... 110 Comment ................................................................. 52 Compatible type....................................................... 48 Composite type........................................................ 48 Compound assignment.......................................... 109 Compound statement ............................................ 112 Conditional operators............................................. 106 const ........................................................................ 61 Constant .................................................................. 49 Constant expressions ............................................ 111 continue statement ................................................ 128 cos ......................................................................... 254 cosf ........................................................................ 277 cosh ....................................................................... 257 coshf ...................................................................... 280 CPU control instruction .................................... 31, 354 ctype ...................................................................... 172
F
fabs ........................................................................269 fabsf .......................................................................292 File scope.................................................................39 float ........................................................................183 Floating-point constant.............................................49 Floating-point type....................................................43 floor ........................................................................270 floorf .......................................................................293 fmod .......................................................................271 fmodf ......................................................................294 for statement ..........................................................125 free .........................................................................217 frexp .......................................................................261 frexpf ......................................................................284 Function declarator ..................................................63 Function definitions ................................................138 Function prototype scope.........................................40 Function scope.........................................................39 Function to change compiler output section name...32 Function type......................................................41, 47 Functions..................................................................25
D
Data insertion function ..................................... 32, 394 Decimal constant ..................................................... 49 Delimiter................................................................... 52 Device type ............................................................ 161 DI ........................................................................... 351 div .................................................................. 185, 223 Division function............................................... 32, 387
G
General integral promotion.......................................72 getchar ...................................................................207 gets ........................................................................208
User's Manual U14872EJ1V0UM
515
APPENDIX E
INDEX
goto statement ....................................................... 127
logf..........................................................................286 Logical AND operator .............................................104 Logical OR operator ...............................................105 longjmp...........................................................185, 191 ltoa..........................................................................227
H
HALT...................................................................... 354 Header file.............................................................. 171 Header name ........................................................... 52 Hexadecimal constant.............................................. 50
M
Machine language ....................................................21 Macro name............................................................161 Macro replacement.................................................153 malloc .....................................................................218 math .......................................................................181 matherr ...................................................................272 memchr ..................................................................239 memcmp.................................................................237 memcpy..................................................................234 memmove...............................................................234 Memory manipulation function..........................33, 415 Memory space ........................................................304 memset...................................................................245 Method of int expansion limitation of argument/return values............................................................33, 406 modf .......................................................................265 modff ......................................................................288 Module name changing function.......................32, 381 Multiplication function .......................................32, 385
I
Identifier ................................................................... 38 if ... else statement................................................. 120 Incomplete type.................................................. 41, 46 Integral type ............................................................. 42 Internal linkage......................................................... 40 Interrupt function .............................................. 31, 351 Interrupt function qualifier ................................ 31, 349 Interrupt functions ............................................ 31, 342 isalnum................................................................... 187 isalpha.................................................................... 187 isascii ..................................................................... 187 iscntrl...................................................................... 187 isdigit...................................................................... 187 isgraph ................................................................... 187 islower.................................................................... 187 isprint ..................................................................... 187 ispunct.................................................................... 187 isspace................................................................... 187 isupper ................................................................... 187 isxdigit .................................................................... 187 Iteration statement ................................................. 112 itoa ......................................................................... 227
N
No linkage ................................................................40 noauto function.......................................................326 noauto functions .......................................................31 NOP........................................................................354 norec function.........................................................330 norec functions .........................................................31
K
Keywords ................................................................. 37
L
Labeled statement ................................................. 112 labs ........................................................................ 222 ldexp ...................................................................... 262 ldexpf ..................................................................... 285 ldiv.................................................................. 185, 223 Library supporting prologue/epilogue............... 33, 435 limits....................................................................... 178 log .......................................................................... 263 log10 ...................................................................... 264 log10f ..................................................................... 287
O
Object type ...............................................................41 Octal constant ..........................................................50
P
Pascal function .................................................32, 402 Pascal function call interface..................................465 peekb......................................................................356 peekw .....................................................................356 Pointer ....................................................................133 Pointer declarator .....................................................62
516
User's Manual U14872EJ1V0UM
APPENDIX E
INDEX
Pointer type.............................................................. 47 pokeb ..................................................................... 356 pokew .................................................................... 356 Postfix operators ...................................................... 78 pow ........................................................................ 266 powf ....................................................................... 289 Preprocessing directive ......................................... 141 printf............................................................... 185, 203 putchar................................................................... 209 puts ........................................................................ 210
sprintf .............................................................185, 194 sqrt .........................................................................267 sqrtf ........................................................................290 srand ..............................................................185, 228 sreg declaration......................................................316 sscanf.............................................................185, 199 Stack change specification.....................................345 Startup routine........................................................375 Start-up routine ......................................................296 static.........................................................................54 Static model .....................................................32, 396 Static model expansion specification ...............33, 422 stdarg .....................................................................174 stddef .....................................................................180 stdio........................................................................174 stdlib.......................................................................175 STOP......................................................................354 Storage class specifier .............................................54 strbrk ......................................................................231 strcat ......................................................................236 strchr ......................................................................240 strcmp ....................................................................238 strcoll......................................................................248 strcpy......................................................................235 strcspn....................................................................241 strerror....................................................................246 string ......................................................................177 String literal ..............................................................51 stritoa .....................................................................233 strlen ......................................................................247 strltoa .....................................................................233 strncat ....................................................................236 strncmp ..................................................................238 strncpy....................................................................235 strpbrk ....................................................................242 strrchr .....................................................................240 strsbrk ....................................................................232 strspn .....................................................................241 strstr .......................................................................243 strtod ..............................................................185, 225 strtok ..............................................................185, 244 strtol .......................................................................213 strtoul .....................................................................213 struct ......................................................................132 Structure.................................................................132 Structure pointers...................................................133 Structure specifier ....................................................57 Structure type ...........................................................47
Q
qsort....................................................................... 230
R
rand................................................................ 185, 228 realloc .................................................................... 219 Re-entrant.............................................................. 185 register............................................................. 54, 312 Register bank......................................................... 304 Register direct reference function.................... 33, 411 Register variables ............................................ 30, 312 Relational operators................................................. 95 return statement..................................................... 130 rolb......................................................................... 382 rolw ........................................................................ 382 ROMization-related section name.......................... 375 rorb ........................................................................ 382 rorw........................................................................ 382 Rotate function................................................. 32, 382 RTOS ..................................................................... 300
S
sbrk ................................................................ 185, 224 Scalar type............................................................... 47 scanf .............................................................. 185, 204 Selection statement ............................................... 112 setjmp .................................................... 173, 185, 191 sfr area............................................................. 30, 323 sfr variable ............................................................. 323 Shift operators ......................................................... 93 Signed integral type ................................................. 43 Simple assignment ................................................ 108 sin .......................................................................... 255 sinf ......................................................................... 278 sinh ........................................................................ 258 sinhf ....................................................................... 281
User's Manual U14872EJ1V0UM
517
APPENDIX E
INDEX
Structure variable................................................... 132 strultoa ................................................................... 233 strxfrm .................................................................... 249 switch statement .................................................... 121
U
ultoa........................................................................227 Unary operators........................................................84 union.......................................................................134 Union ......................................................................134 Union type ................................................................47 Unsigned integral type..............................................43 Usage of saddr area ...............................................316 Usage of saddr area .................................................30
T
Tags ......................................................................... 60 tan .......................................................................... 256 tanf ......................................................................... 279 tanh ........................................................................ 259 tanhf ....................................................................... 282 Temporary variables ........................................ 33, 432 toascii..................................................................... 189 tolow....................................................................... 190 tolower ................................................................... 188 toup ........................................................................ 190 toupper................................................................... 188 Trigraph sequence ................................................... 36 Type modification............................................. 32, 400 Type names ............................................................. 64 Type specifier........................................................... 55 typedef ..................................................................... 54
V
va_arg.....................................................................192 va_end....................................................................192 va_start...................................................................192 void ...........................................................................74 void pointer ...............................................................74 volatile ......................................................................61 vprintf..............................................................185, 205 vsprintf ............................................................185, 206
W
while statement.......................................................123
518
User's Manual U14872EJ1V0UM
[MEMO]
User's Manual U14872EJ1V0UM
519
Facsimile Message
From:
Name Company
Although NEC has taken all possible steps to ensure that the documentation supplied to our customers is complete, bug free and up-to-date, we readily accept that errors may occur. Despite all the care and precautions we've taken, you may encounter problems in the documentation. Please complete this form whenever you'd like to report errors or suggest improvements to us.
Tel.
FAX
Address
Thank you for your kind support.
North America Hong Kong, Philippines, Oceania NEC Electronics Inc. NEC Electronics Hong Kong Ltd. Corporate Communications Dept. Fax: +852-2886-9022/9044 Fax: 1-800-729-9288 1-408-588-6130 Korea Europe NEC Electronics Hong Kong Ltd. NEC Electronics (Europe) GmbH Seoul Branch Technical Documentation Dept. Fax: 02-528-4411 Fax: +49-211-6503-274 South America NEC do Brasil S.A. Fax: +55-11-6462-6829 Taiwan NEC Electronics Taiwan Ltd. Fax: 02-2719-5951 Asian Nations except Philippines NEC Electronics Singapore Pte. Ltd. Fax: +65-250-3583
Japan NEC Semiconductor Technical Hotline Fax: 044-435-9608
I would like to report the following error/make the following suggestion: Document title: Document number: Page number:
If possible, please fax the referenced page or drawing. Document Rating Clarity Technical Accuracy Organization
CS 00.6
Excellent
Good
Acceptable
Poor


▲Up To Search▲   

 
Price & Availability of CC78K0S

All Rights Reserved © IC-ON-LINE 2003 - 2022  

[Add Bookmark] [Contact Us] [Link exchange] [Privacy policy]
Mirror Sites :  [www.datasheet.hk]   [www.maxim4u.com]  [www.ic-on-line.cn] [www.ic-on-line.com] [www.ic-on-line.net] [www.alldatasheet.com.cn] [www.gdcy.com]  [www.gdcy.net]


 . . . . .
  We use cookies to deliver the best possible web experience and assist with our advertising efforts. By continuing to use this site, you consent to the use of cookies. For more information on cookies, please take a look at our Privacy Policy. X